@unbrained/pm-cli 2026.11.27 → 2026.11.28

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 (176) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli-bundle/bundle-manifest.json +1 -1
  3. package/dist/cli-bundle/chunks/{chunk-SIRZ4VMT.js → chunk-2YD2AERA.js} +2 -2
  4. package/dist/cli-bundle/chunks/{chunk-WY7467RY.js → chunk-54AQJTUH.js} +2 -2
  5. package/dist/cli-bundle/chunks/chunk-56DKWGHE.js +2 -0
  6. package/dist/cli-bundle/chunks/chunk-56GUDMXN.js +113 -0
  7. package/dist/cli-bundle/chunks/chunk-5ECCMDSU.js +2 -0
  8. package/dist/cli-bundle/chunks/chunk-6RBD2AKU.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-O23KTJL6.js → chunk-C4O5TZY3.js} +46 -46
  10. package/dist/cli-bundle/chunks/chunk-CATRDGAB.js +125 -0
  11. package/dist/cli-bundle/chunks/{chunk-X6TE47CS.js → chunk-CDUV7DFD.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-CTM26LUE.js +4 -0
  13. package/dist/cli-bundle/chunks/chunk-D3I5AHNN.js +2 -0
  14. package/dist/cli-bundle/chunks/chunk-E2LQ6LCJ.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-63AVXDZS.js → chunk-FG4TNQQM.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-JQYPSABI.js +2 -0
  17. package/dist/cli-bundle/chunks/chunk-LMDIKSDZ.js +9 -0
  18. package/dist/cli-bundle/chunks/chunk-LRGYV6QQ.js +2 -0
  19. package/dist/cli-bundle/chunks/chunk-MO6PPUI6.js +2 -0
  20. package/dist/cli-bundle/chunks/chunk-O2SWNEBW.js +8 -0
  21. package/dist/cli-bundle/chunks/{chunk-6NJ3BONB.js → chunk-O2WNNIKK.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-5CMR4R5V.js → chunk-OFIYA3PI.js} +3 -3
  23. package/dist/cli-bundle/chunks/{chunk-ZGV4ZXDS.js → chunk-Q6BGQRCB.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-RGE3XW3A.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-SP6CDM6B.js +31 -0
  26. package/dist/cli-bundle/chunks/{chunk-KS47NGMQ.js → chunk-T7RZPIOB.js} +14 -14
  27. package/dist/cli-bundle/chunks/{chunk-KP75JTTO.js → chunk-T7UTG56V.js} +4 -4
  28. package/dist/cli-bundle/chunks/chunk-TWRUA2NH.js +3 -0
  29. package/dist/cli-bundle/chunks/chunk-WKDKBS4P.js +4 -0
  30. package/dist/cli-bundle/chunks/chunk-YEMFOKFG.js +2 -0
  31. package/dist/cli-bundle/chunks/{chunk-Y5U7QCNX.js → chunk-YLS2N4SN.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-W7SPEGSP.js → chunk-ZXERHBMA.js} +2 -2
  33. package/dist/cli-bundle/chunks/field-definition-losses-JFMMMVTV.js +2 -0
  34. package/dist/cli-bundle/chunks/field-option-collisions-G4LQ2646.js +2 -0
  35. package/dist/cli-bundle/{focused-chunks/item-revision-NOHVIOQQ.js → chunks/item-revision-O7L3AA2W.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-transaction-4XC74ULD.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-A45DFDEO.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-SIUIMAEO.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-Q7UW2EPV.js → register-list-query-FCPGG2UT.js} +2 -2
  40. package/dist/cli-bundle/chunks/{register-mutation-YNW7E3T4.js → register-mutation-VD3JX23I.js} +2 -2
  41. package/dist/cli-bundle/chunks/register-operations-KHJD4GFZ.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-EWAZZWPL.js +2 -0
  43. package/dist/cli-bundle/chunks/runtime-schema-3RAXYNG5.js +2 -0
  44. package/dist/cli-bundle/chunks/{settlement-hook-ESAAEBRM.js → settlement-hook-KWBOSRDZ.js} +2 -2
  45. package/dist/cli-bundle/chunks/stage-UIDZMTE5.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-5MZXU6HB.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-64DSKZJN.js +100 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-N7ZAMULP.js → chunk-7EKKUYN5.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-7P6OGPEG.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-A5B43EWU.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-AHCOSTL7.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-CQLOYNJY.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-E4C6T3NL.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-GUAT4OAC.js → chunk-HCWDMFWA.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-AL47ODFZ.js → chunk-J4V3J5MC.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-JD45Y2BR.js +91 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-KMGI5GZP.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-MSLRDKWL.js +4 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-YPOATPTX.js → chunk-O33WUEAF.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-7FKGIJEB.js → chunk-OEMI52ZS.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-24W63UPP.js → chunk-Q6JCMFGU.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-RBOWKXFV.js +8 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-TF57RHS2.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-REORRDPH.js → chunk-VNU3IFBL.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/chunk-X5ZVPFK7.js +4 -0
  66. package/dist/cli-bundle/focused-chunks/{chunk-52PHSTGP.js → chunk-XVCMYFQU.js} +2 -2
  67. package/dist/cli-bundle/focused-chunks/{chunk-4HLZOOZI.js → chunk-Y7EC2L2G.js} +3 -3
  68. package/dist/cli-bundle/focused-chunks/{chunk-UGQ2EXTU.js → chunk-YC3PFFDE.js} +56 -56
  69. package/dist/cli-bundle/focused-chunks/{chunk-7GZMOLQY.js → chunk-YX75PQFO.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{chunk-AN4NFFLL.js → chunk-Z4FWJGQG.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/chunk-ZHHFOQSL.js +44 -0
  72. package/dist/cli-bundle/focused-chunks/chunk-ZUAPUBJK.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/{chunk-HSWL6L2O.js → chunk-ZYHGQIQ7.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/field-definition-losses-NUZO3JCP.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/field-option-collisions-63YQ2J3N.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/item-revision-PV5O6F5Y.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/item-transaction-S5QXBGAT.js +2 -0
  78. package/dist/cli-bundle/{chunks/mutation-actor-SFYTD2ZB.js → focused-chunks/mutation-actor-2AAUJG2Z.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/mutation-admission-X7HHNERR.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/runtime-schema-5J2ONRNV.js +2 -0
  81. package/dist/cli-bundle/focused-chunks/stage-56RYPMBK.js +2 -0
  82. package/dist/cli-bundle/main.js +2 -2
  83. package/dist/cli-bundle/sdk-authoring.js +1 -1
  84. package/dist/cli-bundle/sdk-contracts.js +1 -1
  85. package/dist/cli-bundle/sdk-core.js +1 -1
  86. package/dist/cli-bundle/sdk-governance.js +1 -1
  87. package/dist/cli-bundle/sdk-graph.js +1 -1
  88. package/dist/cli-bundle/sdk-merge.js +63 -63
  89. package/dist/cli-bundle/sdk-query.js +1 -1
  90. package/dist/cli-bundle/sdk-runtime.js +1 -1
  91. package/dist/cli-bundle/sdk-testing.js +1 -1
  92. package/dist/cli-bundle/sdk.js +2 -2
  93. package/dist/core/extensions/item-fields.d.ts +15 -1
  94. package/dist/core/extensions/item-fields.js +1 -1
  95. package/dist/core/extensions/loader.js +1 -1
  96. package/dist/core/profile/profile-lint.js +1 -1
  97. package/dist/core/schema/runtime-schema.d.ts +20 -1
  98. package/dist/core/schema/runtime-schema.js +2 -2
  99. package/dist/sdk/agent/refusal-reachability.d.ts +1 -1
  100. package/dist/sdk/extension/command-options.d.ts +8 -0
  101. package/dist/sdk/extension/command-options.js +1 -1
  102. package/dist/sdk/extension-command-context.js +2 -2
  103. package/dist/sdk/governance/validate.js +1 -1
  104. package/dist/sdk/lifecycle/create.js +1 -1
  105. package/dist/sdk/lifecycle/update.js +2 -2
  106. package/dist/sdk/profile.js +1 -1
  107. package/dist/sdk/read-output-contracts.js +1 -1
  108. package/dist/sdk/schema/field-definition-losses.js +2 -0
  109. package/dist/sdk/schema/field-option-collisions.js +1 -1
  110. package/dist/sdk/schema.js +2 -2
  111. package/docs/COMMANDS.md +1 -1
  112. package/docs/CONFIGURATION.md +2 -0
  113. package/docs/EXTENSIONS.md +1 -1
  114. package/docs/SDK_AUDITED_MUTATIONS.md +12 -3
  115. package/marketplace.json +1 -1
  116. package/package.json +1 -1
  117. package/packages/pm-beads/package.json +1 -1
  118. package/packages/pm-calendar/package.json +1 -1
  119. package/packages/pm-command-kit/package.json +1 -1
  120. package/packages/pm-digital-twin/package.json +1 -1
  121. package/packages/pm-governance-audit/package.json +1 -1
  122. package/packages/pm-guide-shell/package.json +1 -1
  123. package/packages/pm-kanban/package.json +1 -1
  124. package/packages/pm-lifecycle-hooks/package.json +1 -1
  125. package/packages/pm-linked-test-adapters/package.json +1 -1
  126. package/packages/pm-search-advanced/package.json +1 -1
  127. package/packages/pm-templates/package.json +1 -1
  128. package/packages/pm-todos/package.json +1 -1
  129. package/packages/pm-vcs/package.json +1 -1
  130. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  131. package/plugins/pm-claude/package.json +1 -1
  132. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  133. package/plugins/pm-codex/package.json +1 -1
  134. package/plugins/pm-codex/plugin.json +1 -1
  135. package/runtime-dependencies.json +1 -1
  136. package/dist/cli-bundle/chunks/chunk-5M7UTO2G.js +0 -2
  137. package/dist/cli-bundle/chunks/chunk-66TNCHHG.js +0 -2
  138. package/dist/cli-bundle/chunks/chunk-AVHRMUXJ.js +0 -3
  139. package/dist/cli-bundle/chunks/chunk-HTT52JL3.js +0 -125
  140. package/dist/cli-bundle/chunks/chunk-J25DZRYJ.js +0 -31
  141. package/dist/cli-bundle/chunks/chunk-J6TFG34A.js +0 -4
  142. package/dist/cli-bundle/chunks/chunk-JX475QVU.js +0 -3
  143. package/dist/cli-bundle/chunks/chunk-OFX2VA5Z.js +0 -2
  144. package/dist/cli-bundle/chunks/chunk-QVDEZBSV.js +0 -8
  145. package/dist/cli-bundle/chunks/chunk-SX76UGEY.js +0 -3
  146. package/dist/cli-bundle/chunks/chunk-VC4BJIA7.js +0 -9
  147. package/dist/cli-bundle/chunks/chunk-XB6QEVUK.js +0 -2
  148. package/dist/cli-bundle/chunks/chunk-XYX4CXFR.js +0 -2
  149. package/dist/cli-bundle/chunks/chunk-YGK6SA7P.js +0 -2
  150. package/dist/cli-bundle/chunks/chunk-ZILIHDDY.js +0 -113
  151. package/dist/cli-bundle/chunks/field-option-collisions-UL6BIPAK.js +0 -2
  152. package/dist/cli-bundle/chunks/item-revision-WNUDY5DM.js +0 -2
  153. package/dist/cli-bundle/chunks/item-transaction-ER3OWOPV.js +0 -2
  154. package/dist/cli-bundle/chunks/mutation-admission-AVOOT3KH.js +0 -2
  155. package/dist/cli-bundle/chunks/register-operations-DAUTQCIO.js +0 -2
  156. package/dist/cli-bundle/chunks/register-setup-VSURGF7V.js +0 -2
  157. package/dist/cli-bundle/chunks/runtime-schema-Y4SHTEXL.js +0 -2
  158. package/dist/cli-bundle/chunks/stage-N5GDBS5A.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-2XGHBYDA.js +0 -44
  160. package/dist/cli-bundle/focused-chunks/chunk-3QRMY6KF.js +0 -2
  161. package/dist/cli-bundle/focused-chunks/chunk-B2HJI6KA.js +0 -2
  162. package/dist/cli-bundle/focused-chunks/chunk-C2HW7BSE.js +0 -2
  163. package/dist/cli-bundle/focused-chunks/chunk-GISZWMBS.js +0 -2
  164. package/dist/cli-bundle/focused-chunks/chunk-H4JBS477.js +0 -2
  165. package/dist/cli-bundle/focused-chunks/chunk-HGJ4MILN.js +0 -100
  166. package/dist/cli-bundle/focused-chunks/chunk-I4GY7HAP.js +0 -3
  167. package/dist/cli-bundle/focused-chunks/chunk-KMG4O2IU.js +0 -4
  168. package/dist/cli-bundle/focused-chunks/chunk-OCKKIECS.js +0 -3
  169. package/dist/cli-bundle/focused-chunks/chunk-SXWUKNTY.js +0 -8
  170. package/dist/cli-bundle/focused-chunks/chunk-ZZYJS74B.js +0 -91
  171. package/dist/cli-bundle/focused-chunks/field-option-collisions-BP7ILGQK.js +0 -2
  172. package/dist/cli-bundle/focused-chunks/item-transaction-O26COBOJ.js +0 -2
  173. package/dist/cli-bundle/focused-chunks/mutation-actor-HVJV5S76.js +0 -2
  174. package/dist/cli-bundle/focused-chunks/mutation-admission-JRICEVYN.js +0 -2
  175. package/dist/cli-bundle/focused-chunks/runtime-schema-YXPYDD2C.js +0 -2
  176. package/dist/cli-bundle/focused-chunks/stage-NSX6ASBZ.js +0 -2
@@ -1,14 +1,14 @@
1
- import{$c as ed,$d as wd,Fa as Jc,Fb as Gl,Ga as Gn,H as Wc,I as Vc,Ib as Ul,Jb as ql,K as Kc,Oa as bl,Ob as Vt,Pc as pr,Pd as xr,Sc as Ce,Sd as yd,Tc as Zl,Yc as fr,Zc as _r,_c as Ql,_d as bd,ad as lt,b as nr,bd as td,d as Me,e as Ec,ec as Vn,ed as rd,fd as id,g as rt,ga as je,gd as sd,h as Cc,hd as ad,i as or,ib as Al,id as yr,j as Ln,jb as xl,jd as br,kd as wr,lc as Hl,nc as Bl,nd as md,o as it,ob as cr,od as pd,pb as lr,pd as ud,qb as dr,qd as fd,rd as _d,sb as Il,tb as El,tc as Kn,td as hd,ub as mr,ud as gd,vc as Kt,y as Hc,z as Bc}from"./chunk-J25DZRYJ.js";import{A as Bt,B as Mc,C as Dc,D as ir,E as Wt,F as Mn,G as De,H as jc,I as sr,J as U,K as ar,L as j,M as Gc,N as Uc,O as Dn,Q as qc,R as jn,S as zc,n as Ht,o as Oc,p as $c,q as Fc,s as rr,t as st,u as h,v as Pc,w as Nc,y as Y,z as Lc}from"./chunk-YGK6SA7P.js";import{a as ct,b as Hn,c as wl,d as vl,g as kl,i as Wl}from"./chunk-AVHRMUXJ.js";import{A as tl,Ba as gl,C as nl,D as ol,E as rl,Ea as yl,F as il,G as sl,H as al,I as cl,J as ll,K as dl,L as ml,M as pl,N as ul,O as fl,P as _l,Q as hl,d as Da,ka as at,m as Un,o as Ge,p as Zc,q as qn,r as Qc,x as el,xa as zn}from"./chunk-KS47NGMQ.js";import{i as Yc,o as Xc}from"./chunk-5CMR4R5V.js";import{L as Ar,U as ld,a as Vl,c as Kl,d as Jl,e as Yl,k as Xl,l as Jt,m as vr,n as kr,u as Sr,w as cd}from"./chunk-6NJ3BONB.js";import{$a as Ue,Ha as Cl,Jc as hr,Lb as nd,Mb as od,Oc as gr,Ra as Rl,Rc as dd,Sa as Tl,Ta as Ol,U as _e,Wa as $l,Xa as Fl,Ya as Pl,Za as Nl,aa as Sl,ab as Ll,b as Ma,bb as Ml,db as Dl,fb as Bn,hb as jl,lb as Ee,mb as zl,nb as Wn,rb as ur}from"./chunk-KP75JTTO.js";import{a as Na,b as La}from"./chunk-J6TFG34A.js";import{_ as Tc,a as xc,b as Ic,l as Rc}from"./chunk-X6TE47CS.js";import{r as ot}from"./chunk-OFX2VA5Z.js";import{A as pn,Ab as qt,Ba as oa,Bb as ya,C as ss,Db as Ko,Ea as ue,Fb as Jo,Ha as ra,Ia as ia,Jb as ba,Ka as In,Kb as wa,L as _n,La as sa,Lb as va,M as hn,Mb as ka,N as gn,Nb as Sa,O as yn,P as fs,Pb as Aa,Qb as xa,R as ae,Ra as da,Rb as Ia,Sa as ma,Sb as zt,T as pe,Tb as Ea,Ub as $n,Vb as Ca,Vc as $a,Wb as Yo,X as Ys,Xb as Xo,Yb as Ra,Z as Xs,Za as Vo,_ as Zs,a as Xi,aa as Qs,ba as ea,eb as Cn,gb as Rn,i as $t,j as Zi,k as Qi,ka as zo,l as es,la as Ho,m as ts,mb as ua,ob as fa,od as Qo,pb as _a,pc as Zo,qb as oe,qd as er,ra as xn,rb as xe,s as ns,t as Ao,tc as Ta,td as Fa,u as os,ub as Ut,uc as Oa,ud as Pa,v as le,wb as Tn,x as rs,xa as na,xb as On,y as is,yb as ga}from"./chunk-HTT52JL3.js";import{C as pa,H as ha,I as P,f as ta,g as tt,k as En,m as aa,n as nt,p as ca,s as Bo,t as Wo,v as I,w as la}from"./chunk-VC4BJIA7.js";import{Ab as Lt,Ah as Go,Bb as Mt,Bh as Uo,Ca as ms,Ch as qo,Dc as Po,Dh as T,Fa as Ae,Gg as Ds,Hg as js,I as mn,Ia as $o,Ig as Gs,Je as Os,Jg as Us,Kg as qs,Kh as Ws,La as Nt,Lg as zs,Lh as Vs,Mb as Le,Me as $s,Mg as Hs,Nb as Dt,Oh as G,Pe as Fs,Rh as An,Sd as Es,Tf as jt,Ub as Ss,Uf as Gt,V as F,Vb as As,Vh as Ks,W as un,Wb as xs,We as Ps,Wh as Js,a as dn,ba as x,df as Ns,ea as Se,ed as H,fa as Oo,gf as Qe,ha as me,jb as Ne,ke as Cs,kf as Ls,kh as vn,lb as Ze,lh as kn,mc as Fo,mh as Sn,nc as C,ob as ws,oh as Bs,pg as wn,rb as vs,sb as ks,sc as Is,u as Ki,ua as ls,ue as Rs,ug as et,uh as No,v as Ji,va as ds,wh as Lo,xe as Ts,xh as Mo,y as Yi,yg as Ms,yh as Do,zb as bn,zh as jo}from"./chunk-ZILIHDDY.js";import{a as fe,b as yc,c as Nn,d as bc,g as wc,i as vc,j as kc,k as Sc,m as Ac}from"./chunk-JX475QVU.js";import{$a as dc,C as Ga,Da as Za,F as Ua,Fa as Qa,G as Fn,H as qa,La as ec,Ma as tc,N as za,Na as nc,Qa as oc,R as Ha,Ua as rc,Va as ic,W as Ba,Wa as sc,X as Wa,Xa as ac,Ya as cc,Z as Va,_a as lc,aa as Ka,ab as mc,bb as pc,cb as uc,db as fc,gb as _c,hb as Pn,ib as hc,j as tr,jb as gc,nb as Ie,ob as E,ra as Ja,t as ja,ua as Ya,va as Xa}from"./chunk-63AVXDZS.js";import{D as cs,Q as S,U as ps,W as us,a as Ot,b as ee,ha as bs,i as J,k as So,m as Vi,v as as,x as fn}from"./chunk-WY7467RY.js";import{E as Ye,F as Fe,H as _s,J as hs,K as Pe,L as gs,O as W,Q as Xe,R as ys,a as Pt,c as Io,v as Eo,w as Co,x as Ro,y as To}from"./chunk-SX76UGEY.js";import{A as u,C as p,E as ke,F as Je,G as xo,H as de,K as se,M as Ft,a as Ui,e as qi,f as zi,g as Hi,i as Bi,m as Wi}from"./chunk-6OIHST4I.js";import{AsyncLocalStorage as tb}from"node:async_hooks";import{realpathSync as nb}from"node:fs";import Mi from"node:path";import{readFile as Su}from"node:fs/promises";import Au from"node:path";var Ir="context-intents.json";function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xu(e,t,n){if(!Jn(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(r=>typeof r=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function vd(e,t){let n=Array.isArray(e)?e:Jn(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,r)=>xu(o,t,r))}async function Iu(e){let t=Au.join(e,Ir),n;try{n=await Su(t,"utf8")}catch(r){if(Je(r))return[];throw await ha(e),r}let o;try{o=JSON.parse(n)}catch(r){let i=r instanceof Error?r.message:String(r);throw new TypeError(`Invalid ${Ir}: ${i}`,{cause:r})}return vd(o,Ir)}function Eu(e){if(!Jn(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Jn(n)?n.contextIntents??n.context_intents:void 0}function Cu(e){return e.flatMap(t=>{let n=Eu(t.module);return n===void 0?[]:vd(n,`package ${t.name}`)})}async function Ru(e){let t=await Iu(e.pmRoot),n=Cu(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Er(e,t){let n=await Ru(e);return await Ns(n,t)}async function kd(e,t,n=Ps){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,r=Array.isArray(o.warnings)?o.warnings.filter(i=>typeof i=="string"):[];o.warnings=[...new Set([...r,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as Du}from"node:crypto";var Yt=class extends RangeError{code;work;minimum_tokens;constructor(t,n,o){super(t),this.name="OutputEnvelopeFitError",this.code=t,this.work=Object.freeze({...n}),this.minimum_tokens=o}};function Cr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`${t} must be a positive safe integer`)}function Tu(e,t,n,o){return t.map(([r,i])=>{if(o.render_calls>=o.max_render_calls)throw new Yt("output_envelope_work_limit",o);o.render_calls+=1;let s=i(e);if(typeof s!="string")throw new TypeError("Envelope renderers must return strings");let a=n(s);if(!Number.isSafeInteger(a)||a<0)throw new RangeError("Envelope token estimates must be non-negative safe integers");return{name:r,text:s,bytes:Buffer.byteLength(s,"utf8"),estimated_tokens:a}})}function Sd(e,t,n,o){let r=t,i=Object.entries(n.renderers),s=n.estimateTokens??(a=>Es(Buffer.byteLength(a,"utf8")));for(let a=0;a<(n.maxStabilizationPasses??16);a+=1){let c=Object.freeze({...r}),l={...n.buildEnvelope(e,c),output_fit:c},d=Tu(l,i,s,o),m=Math.max(...d.map(g=>g.bytes)),f=Math.max(...d.map(g=>g.estimated_tokens));if(m===r.output_bytes&&f===r.estimated_tokens)return{envelope:l,renderings:d};r={...r,output_bytes:m,estimated_tokens:f}}throw new Yt("output_envelope_unstable",o)}function Ad(e,t){Cr(t.tokenBudget,"tokenBudget"),Cr(t.maxRenderCalls??1e4,"maxRenderCalls"),Cr(t.maxStabilizationPasses??16,"maxStabilizationPasses");let n=t.policy??"prefix";if(n!=="prefix"&&n!=="skip")throw new TypeError("Unknown output envelope fit policy");if(Object.entries(t.renderers).length===0||Object.entries(t.renderers).some(([c,l])=>!c.trim()||typeof l!="function"))throw new TypeError("Envelope fitting requires named callable renderers");let o={evaluated_candidates:0,render_calls:0,max_render_calls:t.maxRenderCalls??1e4},r=[],i=[],s=c=>({version:1,policy:n,total_candidates:e.length,included_indices:Object.freeze([...c]),omitted_count:e.length-c.length,token_budget:t.tokenBudget,estimated_tokens:0,output_bytes:0}),a=Sd(r,s(i),t,o);if(a.envelope.output_fit.estimated_tokens>t.tokenBudget)throw new Yt("output_envelope_infeasible",o,a.envelope.output_fit.estimated_tokens);for(let[c,l]of e.entries()){o.evaluated_candidates+=1;let d=[...r,l],m=[...i,c],f=Sd(d,s(m),t,o);if(f.envelope.output_fit.estimated_tokens<=t.tokenBudget)r=d,i=m,a=f;else if(n==="prefix")break}return{rows:r,...a,complete:r.length===e.length,work:Object.freeze({...o})}}import{constants as Xt}from"node:fs";import{lstat as xd,mkdir as Tr,open as Id}from"node:fs/promises";import he from"node:path";function Rr(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function Or(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function Ou(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function $u(e,t,n,o){let r=n.require(e.kind),i=o.outgoingOne.get(`${r.kind}\0${e.source}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=o.incomingOne.get(`${r.kind}\0${e.target}`);if(s!==void 0&&s!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let a=Or(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function Fu(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function Pu(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=Rr(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:Rr(e.relationshipId,"relationshipId"),author:Rr(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Nu(e,t,n,o,r,i){let s=n.has(t);if(e.action==="add"&&s)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let l=new et([a,c],[e.edge],r).edges()[0];return $u(l,t,r,i),Ou(l)}var Zt=class{#t;#n;#o=[];#i=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??wn()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,r=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let i=n-1;i<o;i+=r)yield Object.freeze(this.#o.slice(i,Math.min(i+r,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let r=t,i=0,s;for(let a of this.stream({...o,batchSize:256}))for(let c of a)r=n(r,c),i+=1,s=c;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:i,...s===void 0?{}:{asOf:s.timestamp}})}#s(t,n){let o=this.#n.require(n.kind);this.#r.identities.set(Or(n,this.#n),t),o.outgoing==="one"&&this.#r.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#r.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#r.identities.delete(Or(t,this.#n)),n.outgoing==="one"&&this.#r.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#r.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=Pu(t,this.version,this.#i),o=this.#e.get(n.relationshipId),r=Nu(t,n.relationshipId,this.#e,this.#t,this.#n,this.#r),i=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...r===void 0?{}:{edge:r},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(i),this.#i.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,r),this.#s(n.relationshipId,r)),i}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let i=Date.parse(t.atTimestamp);if(!Number.isFinite(i))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(s=>Date.parse(s.timestamp)<=i)}else{let i=t.atVersion??this.version;if(!Number.isInteger(i)||i<0||i>this.version)throw new TypeError(`Relationship snapshot version out of range: ${i}`);n=this.#o.slice(0,i)}let o=Fu(n),r=new et(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=Os("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number($s(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=Fs(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:i=>i.eventId,snapshot:String(o)});return{version:o,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},Lu="relationship-event-store",Ed=Xt.O_NOFOLLOW;function Yn(e){return Le(e,Lu,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function qe(e,t="relationships/events.jsonl"){let n=he.resolve(e),o=he.resolve(n,t),r=he.relative(n,o);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${he.sep}`)||he.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await Tr(n,{recursive:!0}),(await xd(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let s=n;for(let a of r.split(he.sep)){s=he.join(s,a);try{if((await xd(s)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(xo(c))break;throw c}}return o}async function Xn(e,t,n){let o=new Zt(t,{registry:n}),r,i;try{i=await Id(e,Xt.O_RDONLY|Ed),r=await i.readFile("utf8")}catch(a){if(xo(a))return{log:o,raw:""};throw a}finally{await i?.close()}let s=r.split(`
2
- `);for(let a=0;a<s.length;a+=1){let c=s[a].trim();if(!c)continue;let l;try{l=JSON.parse(c)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${a+1}`)}if(l.sequence!==o.version+1)throw new TypeError(`Invalid relationship event sequence at line ${a+1}`);o.append({eventId:l.eventId,relationshipId:l.relationshipId,action:l.action,...l.edge===void 0?{}:{edge:l.edge},author:l.author,timestamp:l.timestamp,...l.reason===void 0?{}:{reason:l.reason},expectedVersion:o.version})}return{log:o,raw:r}}function Mu(e,t,n,o){let r=Date.parse(t.timestamp),i;return t.action!=="remove"&&t.edge!==void 0&&(i=new et(n,[t.edge],o).edges()[0]),e.eventId===t.eventId.trim()&&e.relationshipId===t.relationshipId.trim()&&e.action===t.action&&e.author===t.author.trim()&&Number.isFinite(r)&&e.timestamp===new Date(r).toISOString()&&e.reason===(t.reason?.trim()||void 0)&&Ot(e.edge)===Ot(i)}var Zn=class e{#t;#n;#o;#i;#e;constructor(t,n,o,r){this.#t=t.pmRoot,this.#n=n,this.#o=t.registry,this.#i=o,this.#e=r}static async open(t){let n=Object.freeze([...t.nodes]),o=await qe(t.pmRoot,t.relativePath),r=await Yn(t.pmRoot);try{await qe(t.pmRoot,o);let{log:i}=await Xn(o,n,t.registry);return new e(t,n,o,i)}finally{await r()}}get path(){return this.#i}async currentVersion(){return this.#e=await this.#r(),this.#e.version}async append(t){let n=await Yn(this.#t);try{let o=await qe(this.#t,this.#i),{log:r}=await Xn(o,this.#n,this.#o),i=r.append(t);await Tr(he.dirname(o),{recursive:!0}),await qe(this.#t,o);let s=await Id(o,Xt.O_APPEND|Xt.O_CREAT|Xt.O_WRONLY|Ed);try{await s.appendFile(`${JSON.stringify(i)}
3
- `,"utf8")}finally{await s.close()}return this.#e=r,i}finally{await n()}}async appendBatch(t,n={}){let o=await Yn(this.#t);try{let r=await qe(this.#t,this.#i),{log:i,raw:s}=await Xn(r,this.#n,this.#o),a=i.version,c=new Map(i.events().map(m=>[m.eventId,m])),l=[],d=[];for(let m of t){let f=m.eventId.trim(),g=c.get(f);if(g!==void 0){if(n.existingEventPolicy==="skip_identical"&&Mu(g,m,this.#n,this.#o)){d.push(g.eventId);continue}if(n.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${f}`)}let y=i.append(m);c.set(y.eventId,y),l.push(y)}if(l.length>0){let m=s.length===0||s.endsWith(`
1
+ import{L as Ar,U as ld,a as Vl,c as Kl,d as Jl,e as Yl,k as Xl,l as Jt,m as vr,n as kr,u as Sr,w as cd}from"./chunk-O2WNNIKK.js";import{$c as ed,$d as wd,Fa as Jc,Fb as Gl,Ga as Gn,H as Wc,I as Vc,Ib as Ul,Jb as ql,K as Kc,Oa as bl,Ob as Vt,Pc as pr,Pd as xr,Sc as Ce,Sd as yd,Tc as Zl,Yc as fr,Zc as _r,_c as Ql,_d as bd,ad as lt,b as nr,bd as td,d as Me,e as Ec,ec as Vn,ed as rd,fd as id,g as rt,ga as je,gd as sd,h as Cc,hd as ad,i as or,ib as Al,id as yr,j as Ln,jb as xl,jd as br,kd as wr,lc as Hl,nc as Bl,nd as md,o as it,ob as cr,od as pd,pb as lr,pd as ud,qb as dr,qd as fd,rd as _d,sb as Il,tb as El,tc as Kn,td as hd,ub as mr,ud as gd,vc as Kt,x as Hc,y as Bc}from"./chunk-SP6CDM6B.js";import{$a as Ue,Ha as Cl,Jc as hr,Lb as nd,Mb as od,Oc as gr,Ra as Rl,Rc as dd,Sa as Tl,Ta as Ol,U as _e,Wa as $l,Xa as Fl,Ya as Pl,Za as Nl,aa as Sl,ab as Ll,b as ja,bb as Ml,db as Dl,fb as Bn,hb as jl,lb as Ee,mb as zl,nb as Wn,rb as ur}from"./chunk-T7UTG56V.js";import{A as Bt,B as Mc,C as Dc,D as ir,E as Wt,F as Mn,G as De,H as jc,I as sr,J as U,K as ar,L as j,M as Gc,N as Uc,O as Dn,Q as qc,R as jn,S as zc,n as Ht,o as Oc,p as $c,q as Fc,s as rr,t as st,u as h,v as Pc,w as Nc,y as X,z as Lc}from"./chunk-LRGYV6QQ.js";import{a as ct,b as Hn,c as wl,d as vl,g as kl,i as Wl}from"./chunk-TWRUA2NH.js";import{A as tl,Ba as gl,C as nl,D as ol,E as rl,Ea as yl,F as il,G as sl,H as al,I as cl,J as ll,K as dl,L as ml,M as pl,N as ul,O as fl,P as _l,Q as hl,d as Ga,ka as at,m as Un,o as Ge,p as Zc,q as qn,r as Qc,x as el,xa as zn}from"./chunk-T7RZPIOB.js";import{a as Ma,b as Da}from"./chunk-CTM26LUE.js";import{i as Yc,o as Xc}from"./chunk-OFIYA3PI.js";import{_ as Tc,a as xc,b as Ic,l as Rc}from"./chunk-CDUV7DFD.js";import{r as ot}from"./chunk-56DKWGHE.js";import{A as pn,Aa as fe,Bb as Jo,C as ss,Da as sa,Ea as aa,Fb as va,Ga as En,Gb as ka,Ha as ca,Hb as Sa,Ib as Aa,Jb as xa,L as _n,Lb as Ia,M as hn,Mb as Ea,N as gn,Na as pa,Nb as Ca,O as yn,Oa as ua,Ob as zt,P as fs,Pb as Ra,Qb as Fn,R as ae,Rb as Ta,Rc as Pa,Sb as Yo,T as Zs,Tb as Xo,Ub as Oa,V as Qs,Va as Vo,W as ea,Y as ta,Z as na,a as Xi,ab as Rn,cb as Tn,ga as zo,ha as Ho,i as $t,ib as _a,j as Zi,k as Qi,kb as ha,kd as Qo,l as es,lb as ga,lc as Zo,m as ts,mb as oe,md as er,na as In,nb as xe,pc as $a,pd as Na,qb as Ut,qc as Fa,qd as La,s as ns,sb as On,t as Ao,ta as ra,tb as $n,u as os,ub as ba,v as le,wb as qt,x as rs,xa as ia,xb as wa,y as is,zb as Ko}from"./chunk-CATRDGAB.js";import{A as fa,F as ya,G as P,f as oa,g as tt,k as la,l as nt,n as da,q as Bo,r as Wo,t as I,u as ma}from"./chunk-LMDIKSDZ.js";import{b as Cn}from"./chunk-YEMFOKFG.js";import{$f as Gs,$g as qo,Be as Qe,Ea as Ne,Fd as Ts,Fe as Ds,Ga as Ze,Hb as Fo,I as mn,Ib as C,Ja as ks,Jg as kn,Kf as vn,Kg as Sn,Lg as An,Ma as Ss,Na as As,Nb as Cs,Ng as Vs,P as ls,Pd as Os,Pf as et,Q as ds,Sd as $s,Tf as js,Tg as No,Ua as wn,Va as Lt,Vg as Lo,Wa as Mt,Wg as Mo,X as ms,Xg as Do,Yb as Po,Yg as jo,Zg as Go,_ as Ae,_g as Uo,a as dn,ag as Us,ah as T,ba as $o,bg as qs,ce as Fs,cg as zs,dg as Hs,ea as Nt,eg as Bs,fb as Le,fe as Ps,fg as Ws,gb as Dt,hg as ue,hh as Ks,ie as Ns,ih as Js,ld as Rs,lh as G,mf as jt,nb as xs,nf as Gt,ob as Is,oh as xn,pb as Es,pe as Ls,sh as Ys,th as Xs,u as Ki,v as Ji,y as Yi,ye as Ms,zc as H}from"./chunk-56GUDMXN.js";import{h as F,i as un,p as x,s as Se,t as Oo,v as me}from"./chunk-D3I5AHNN.js";import{b as wc,d as vc,e as kc,f as Sc,h as Ac}from"./chunk-5ECCMDSU.js";import{$a as pc,C as qa,Da as ec,F as za,Fa as tc,G as Pn,H as Ha,La as nc,Ma as oc,N as Ba,Na as rc,Qa as ic,R as Wa,Ua as sc,Va as ac,W as Va,Wa as cc,X as Ka,Xa as lc,Ya as dc,Z as Ja,_a as mc,aa as Ya,ab as uc,bb as fc,cb as _c,db as hc,gb as gc,hb as Nn,ib as yc,j as tr,jb as bc,nb as Ie,ob as E,ra as Xa,t as Ua,ua as Za,va as Qa}from"./chunk-FG4TNQQM.js";import{D as cs,Q as S,U as ps,W as us,a as Ot,b as J,ha as vs,i as Y,k as So,m as Vi,v as as,x as fn}from"./chunk-54AQJTUH.js";import{E as Ye,G as pe,H as _s,I as bn,J as hs,L as Fe,N as gs,Q as ys,S as Pe,T as bs,W,Y as Xe,Z as ws,a as Pt,c as Io,v as Eo,w as Co,x as Ro,y as To}from"./chunk-WKDKBS4P.js";import{A as u,C as p,E as ke,F as Je,G as xo,H as de,K as se,M as Ft,a as Ui,e as qi,f as zi,g as Hi,i as Bi,m as Wi}from"./chunk-6OIHST4I.js";import{AsyncLocalStorage as ob}from"node:async_hooks";import{realpathSync as rb}from"node:fs";import Mi from"node:path";import{readFile as Au}from"node:fs/promises";import xu from"node:path";var Ir="context-intents.json";function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Iu(e,t,n){if(!Jn(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(r=>typeof r=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function vd(e,t){let n=Array.isArray(e)?e:Jn(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,r)=>Iu(o,t,r))}async function Eu(e){let t=xu.join(e,Ir),n;try{n=await Au(t,"utf8")}catch(r){if(Je(r))return[];throw await ya(e),r}let o;try{o=JSON.parse(n)}catch(r){let i=r instanceof Error?r.message:String(r);throw new TypeError(`Invalid ${Ir}: ${i}`,{cause:r})}return vd(o,Ir)}function Cu(e){if(!Jn(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Jn(n)?n.contextIntents??n.context_intents:void 0}function Ru(e){return e.flatMap(t=>{let n=Cu(t.module);return n===void 0?[]:vd(n,`package ${t.name}`)})}async function Tu(e){let t=await Eu(e.pmRoot),n=Ru(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Er(e,t){let n=await Tu(e);return await Ms(n,t)}async function kd(e,t,n=Ls){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,r=Array.isArray(o.warnings)?o.warnings.filter(i=>typeof i=="string"):[];o.warnings=[...new Set([...r,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as ju}from"node:crypto";var Yt=class extends RangeError{code;work;minimum_tokens;constructor(t,n,o){super(t),this.name="OutputEnvelopeFitError",this.code=t,this.work=Object.freeze({...n}),this.minimum_tokens=o}};function Cr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`${t} must be a positive safe integer`)}function Ou(e,t,n,o){return t.map(([r,i])=>{if(o.render_calls>=o.max_render_calls)throw new Yt("output_envelope_work_limit",o);o.render_calls+=1;let s=i(e);if(typeof s!="string")throw new TypeError("Envelope renderers must return strings");let a=n(s);if(!Number.isSafeInteger(a)||a<0)throw new RangeError("Envelope token estimates must be non-negative safe integers");return{name:r,text:s,bytes:Buffer.byteLength(s,"utf8"),estimated_tokens:a}})}function Sd(e,t,n,o){let r=t,i=Object.entries(n.renderers),s=n.estimateTokens??(a=>Rs(Buffer.byteLength(a,"utf8")));for(let a=0;a<(n.maxStabilizationPasses??16);a+=1){let c=Object.freeze({...r}),l={...n.buildEnvelope(e,c),output_fit:c},d=Ou(l,i,s,o),m=Math.max(...d.map(g=>g.bytes)),f=Math.max(...d.map(g=>g.estimated_tokens));if(m===r.output_bytes&&f===r.estimated_tokens)return{envelope:l,renderings:d};r={...r,output_bytes:m,estimated_tokens:f}}throw new Yt("output_envelope_unstable",o)}function Ad(e,t){Cr(t.tokenBudget,"tokenBudget"),Cr(t.maxRenderCalls??1e4,"maxRenderCalls"),Cr(t.maxStabilizationPasses??16,"maxStabilizationPasses");let n=t.policy??"prefix";if(n!=="prefix"&&n!=="skip")throw new TypeError("Unknown output envelope fit policy");if(Object.entries(t.renderers).length===0||Object.entries(t.renderers).some(([c,l])=>!c.trim()||typeof l!="function"))throw new TypeError("Envelope fitting requires named callable renderers");let o={evaluated_candidates:0,render_calls:0,max_render_calls:t.maxRenderCalls??1e4},r=[],i=[],s=c=>({version:1,policy:n,total_candidates:e.length,included_indices:Object.freeze([...c]),omitted_count:e.length-c.length,token_budget:t.tokenBudget,estimated_tokens:0,output_bytes:0}),a=Sd(r,s(i),t,o);if(a.envelope.output_fit.estimated_tokens>t.tokenBudget)throw new Yt("output_envelope_infeasible",o,a.envelope.output_fit.estimated_tokens);for(let[c,l]of e.entries()){o.evaluated_candidates+=1;let d=[...r,l],m=[...i,c],f=Sd(d,s(m),t,o);if(f.envelope.output_fit.estimated_tokens<=t.tokenBudget)r=d,i=m,a=f;else if(n==="prefix")break}return{rows:r,...a,complete:r.length===e.length,work:Object.freeze({...o})}}import{constants as Xt}from"node:fs";import{lstat as xd,mkdir as Tr,open as Id}from"node:fs/promises";import he from"node:path";function Rr(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function Or(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function $u(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function Fu(e,t,n,o){let r=n.require(e.kind),i=o.outgoingOne.get(`${r.kind}\0${e.source}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=o.incomingOne.get(`${r.kind}\0${e.target}`);if(s!==void 0&&s!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let a=Or(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function Pu(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function Nu(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=Rr(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:Rr(e.relationshipId,"relationshipId"),author:Rr(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Lu(e,t,n,o,r,i){let s=n.has(t);if(e.action==="add"&&s)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let l=new et([a,c],[e.edge],r).edges()[0];return Fu(l,t,r,i),$u(l)}var Zt=class{#t;#n;#o=[];#i=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??vn()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,r=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let i=n-1;i<o;i+=r)yield Object.freeze(this.#o.slice(i,Math.min(i+r,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let r=t,i=0,s;for(let a of this.stream({...o,batchSize:256}))for(let c of a)r=n(r,c),i+=1,s=c;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:i,...s===void 0?{}:{asOf:s.timestamp}})}#s(t,n){let o=this.#n.require(n.kind);this.#r.identities.set(Or(n,this.#n),t),o.outgoing==="one"&&this.#r.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#r.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#r.identities.delete(Or(t,this.#n)),n.outgoing==="one"&&this.#r.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#r.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=Nu(t,this.version,this.#i),o=this.#e.get(n.relationshipId),r=Lu(t,n.relationshipId,this.#e,this.#t,this.#n,this.#r),i=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...r===void 0?{}:{edge:r},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(i),this.#i.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,r),this.#s(n.relationshipId,r)),i}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let i=Date.parse(t.atTimestamp);if(!Number.isFinite(i))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(s=>Date.parse(s.timestamp)<=i)}else{let i=t.atVersion??this.version;if(!Number.isInteger(i)||i<0||i>this.version)throw new TypeError(`Relationship snapshot version out of range: ${i}`);n=this.#o.slice(0,i)}let o=Pu(n),r=new et(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=Fs("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number(Ps(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=Ns(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:i=>i.eventId,snapshot:String(o)});return{version:o,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},Mu="relationship-event-store",Ed=Xt.O_NOFOLLOW;function Yn(e){return Le(e,Mu,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function qe(e,t="relationships/events.jsonl"){let n=he.resolve(e),o=he.resolve(n,t),r=he.relative(n,o);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${he.sep}`)||he.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await Tr(n,{recursive:!0}),(await xd(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let s=n;for(let a of r.split(he.sep)){s=he.join(s,a);try{if((await xd(s)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(xo(c))break;throw c}}return o}async function Xn(e,t,n){let o=new Zt(t,{registry:n}),r,i;try{i=await Id(e,Xt.O_RDONLY|Ed),r=await i.readFile("utf8")}catch(a){if(xo(a))return{log:o,raw:""};throw a}finally{await i?.close()}let s=r.split(`
2
+ `);for(let a=0;a<s.length;a+=1){let c=s[a].trim();if(!c)continue;let l;try{l=JSON.parse(c)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${a+1}`)}if(l.sequence!==o.version+1)throw new TypeError(`Invalid relationship event sequence at line ${a+1}`);o.append({eventId:l.eventId,relationshipId:l.relationshipId,action:l.action,...l.edge===void 0?{}:{edge:l.edge},author:l.author,timestamp:l.timestamp,...l.reason===void 0?{}:{reason:l.reason},expectedVersion:o.version})}return{log:o,raw:r}}function Du(e,t,n,o){let r=Date.parse(t.timestamp),i;return t.action!=="remove"&&t.edge!==void 0&&(i=new et(n,[t.edge],o).edges()[0]),e.eventId===t.eventId.trim()&&e.relationshipId===t.relationshipId.trim()&&e.action===t.action&&e.author===t.author.trim()&&Number.isFinite(r)&&e.timestamp===new Date(r).toISOString()&&e.reason===(t.reason?.trim()||void 0)&&Ot(e.edge)===Ot(i)}var Zn=class e{#t;#n;#o;#i;#e;constructor(t,n,o,r){this.#t=t.pmRoot,this.#n=n,this.#o=t.registry,this.#i=o,this.#e=r}static async open(t){let n=Object.freeze([...t.nodes]),o=await qe(t.pmRoot,t.relativePath),r=await Yn(t.pmRoot);try{await qe(t.pmRoot,o);let{log:i}=await Xn(o,n,t.registry);return new e(t,n,o,i)}finally{await r()}}get path(){return this.#i}async currentVersion(){return this.#e=await this.#r(),this.#e.version}async append(t){let n=await Yn(this.#t);try{let o=await qe(this.#t,this.#i),{log:r}=await Xn(o,this.#n,this.#o),i=r.append(t);await Tr(he.dirname(o),{recursive:!0}),await qe(this.#t,o);let s=await Id(o,Xt.O_APPEND|Xt.O_CREAT|Xt.O_WRONLY|Ed);try{await s.appendFile(`${JSON.stringify(i)}
3
+ `,"utf8")}finally{await s.close()}return this.#e=r,i}finally{await n()}}async appendBatch(t,n={}){let o=await Yn(this.#t);try{let r=await qe(this.#t,this.#i),{log:i,raw:s}=await Xn(r,this.#n,this.#o),a=i.version,c=new Map(i.events().map(m=>[m.eventId,m])),l=[],d=[];for(let m of t){let f=m.eventId.trim(),g=c.get(f);if(g!==void 0){if(n.existingEventPolicy==="skip_identical"&&Du(g,m,this.#n,this.#o)){d.push(g.eventId);continue}if(n.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${f}`)}let y=i.append(m);c.set(y.eventId,y),l.push(y)}if(l.length>0){let m=s.length===0||s.endsWith(`
4
4
  `)?s:`${s}
5
5
  `;await Tr(he.dirname(r),{recursive:!0}),await qe(this.#t,r),await se(r,`${m}${l.map(f=>JSON.stringify(f)).join(`
6
6
  `)}
7
- `)}return this.#e=i,Object.freeze({version_before:a,version_after:i.version,appended:Object.freeze(l),skipped_event_ids:Object.freeze(d)})}finally{await o()}}async snapshot(t={}){return this.#e=await this.#r(),this.#e.snapshot(t)}async page(t){return this.#e=await this.#r(),this.#e.page(t)}async*stream(t={}){this.#e=await this.#r(),yield*this.#e.stream(t)}async project(t,n,o={}){return this.#e=await this.#r(),this.#e.project(t,n,o)}async#r(){let t=await Yn(this.#t);try{let n=await qe(this.#t,this.#i);return(await Xn(n,this.#n,this.#o)).log}finally{await t()}}};function $r(e){let t=wn();for(let n of e)t.register(n);return t}function ju(e,t,n=[]){if(n.length===0)return e;let o=JSON.parse(e),r=JSON.parse(Wo(t));for(let i of n){let s=i.split("."),a=r;for(let d of s){let m=$o(a);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(d)||["constructor","prototype","__proto__"].includes(d)||m===null||!Object.hasOwn(m,d))throw new p(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,u.USAGE);a=m[d]}if($o(a)===null)throw new p(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,u.USAGE);let c=o,l=r;for(let d of s.slice(0,-1)){let m=c[d];l=l[d],m===void 0&&Object.defineProperty(c,d,{value:structuredClone(l),enumerable:!0,writable:!0,configurable:!0}),c=c[d]}Object.defineProperty(c,s.at(-1),{value:a,enumerable:!0,writable:!0,configurable:!0})}return ee(o,JSON.parse(e))?e:`${JSON.stringify(o,null,2)}
8
- `}async function Gu(e,t,n){let o=t.schema?.fields??[];if(o.length===0)return;let{normalizeCliToken:r,resolveRuntimeFieldRegistry:i}=await import("./runtime-schema-Y4SHTEXL.js"),s=f=>i({fields:[f]}).definitions[0],a=f=>JSON.parse(JSON.stringify(f)),c=[...e.schema.fields,...Array.isArray(n)?n:[]].map(f=>({resolved:s(f),persisted:a(f)})),l=f=>[f.cli_flag,...Array.isArray(f.cli_aliases)?f.cli_aliases:[]].some(g=>typeof g=="string"&&r(g).length===0),d=o.filter(f=>{let g=s(f),y=c.some(k=>ee(k.persisted,a(f)));return g===void 0||l(f)?!y:!c.some(k=>ee(k.resolved,g))});if(d.length===0)return;let{assertFieldDefinitionOptionsAvailable:m}=await import("./field-option-collisions-UL6BIPAK.js");for(let f of d)m(f)}function Cd(e,t,n,o){return{fitOutputEnvelope:Ad,client:t,isItemNotFoundError:r=>Zo(r)&&r.exitCode===u.NOT_FOUND,getItemAt:(r,i)=>La(r,i,{pmRoot:e}),readSettingsSection:(r,i)=>Fa(e,r,i),writeSettingsSection:(r,i,s)=>Pa(e,r,i,{author:n,...s}),openRelationshipEventStore:r=>Zn.open({pmRoot:e,nodes:r.nodes,registry:$r(r.definitions),...r.relativePath===void 0?{}:{relativePath:r.relativePath}}),createRelationshipGraph:r=>new et(r.nodes,r.edges,$r(r.definitions)),analyzeRelationshipImpact:(r,i,s)=>Ma(r,i,s),validateRelationshipEvents:r=>{let i=new Zt(r.nodes,{registry:$r(r.definitions)});return r.events.map(s=>i.append({...s,expectedVersion:i.version}))},commitWorkspaceTransaction:r=>Da({...r,pmRoot:e}),mutateWorkspaceSettings:async r=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(r.operationId))throw new p("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",u.USAGE);let i=r.dryRun===!0?await nt(e,()=>I(e)):await I(e);try{let s=await ta({pmRoot:e,filePath:Se(e),op:"extension:pm:settings",idempotencyKey:o===void 0?r.operationId:`${Du("sha256").update(o).digest("hex").slice(0,16)}:${r.operationId}`,author:C(n,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:r.dryRun===!0,mutate:async a=>{let c=a===null?null:JSON.parse(a),l=En(c);if(!l.success)throw new p("Workspace settings mutation requires a valid initialized settings.json.",u.USAGE);let d=Bo(l.data),m=await r.mutate(structuredClone(d));if(!En(m).success)throw new p("Workspace settings mutation returned invalid settings.json.",u.USAGE);await Gu(d,m,c.schema?.fields);let f=ee(d,m)?a:Wo(m,{source:{raw:c,validated:l.data}});f=ju(f,m,r.replaceSubtrees);let g=En(JSON.parse(f));if(!g.success)throw new p("Workspace settings mutation serialized invalid settings.json.",u.USAGE);return{raw:f,result:r.includePreview===!0?Bo(g.data):void 0}}});return s.changed&&r.dryRun!==!0&&await G({path:Se(e),scope:"project",op:"extension:pm:settings"}),{changed:s.changed,dry_run:r.dryRun===!0,replayed:s.replayed===!0,...s.result===void 0?{}:{preview:s.result}}}finally{aa(e)}}}}function Rd(e){return{undeclaredKeys:Jc(e)?"pass":"refuse"}}var Uu=["invalid_envelope","source_incomplete","source_unchecked","filtered_corpus","terminal_items_excluded","strict_read_unproven","page_incomplete","count_mismatch","projection_incomplete","field_omission","omission_receipt_missing","omission_receipt_invalid","read_output_missing","read_output_invalid","read_output_dimensions_incomplete","budget_compaction","budget_omission","session_projection","invalid_item_id","duplicate_item_id"],Qn=class extends Error{receipt;constructor(t,n={}){super(`Complete-list certification failed: ${t.map(r=>r.code).join(", ")}.`),this.name="PmCompleteListValidationError";let o=n.includeBody===!0;this.receipt={contract_version:1,contract:"complete_list",findings:t,recovery:{suggested_retry:`pm list --all --output-include full --strict-read --no-truncate --output-budget unbounded --output-limit unbounded${o?" --include-body":""} --json`,sdk:o?"await client.listAllComplete({ includeBody: true })":"await client.listAllComplete()"}}}};function Fr(e={}){return Cs({excludeTerminal:!1,full:!0,...e.includeBody===void 0?{}:{includeBody:e.includeBody},noTruncate:!0,outputBudget:"unbounded",outputLimit:"unbounded",strictRead:!0},["full"])}function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,t,n,o){t&&e.push({code:n,message:o})}function qu(e,t){let n=re(e.completeness)?e.completeness:{};M(t,n.status==="partial","source_incomplete","The source scan reported unreadable tracker artifacts."),M(t,n.status!=="complete"&&n.status!=="partial","source_unchecked","The source scan did not prove completeness.");let o=n.unreadable_item_count,r=n.unreadable_directory_count;M(t,n.status==="complete"&&(o!==0||r!==0)&&Number.isSafeInteger(o)&&Number.isSafeInteger(r),"source_incomplete","The source scan reports unreadable tracker artifacts despite a complete status."),M(t,n.status==="complete"&&(!Number.isSafeInteger(o)||!Number.isSafeInteger(r)||Number(o)<0||Number(r)<0),"source_unchecked","The source scan did not report safe non-negative unreadable counts.");let i=re(e.filters)?e.filters:{},s=re(i.runtime_filters)?i.runtime_filters:{},a=new Set(["exclude_terminal","include_body","no_truncate","runtime_filters","status","strict_read"]);return M(t,i.status!=="all"||Object.keys(s).length>0||Object.keys(i).some(c=>!a.has(c)),"filtered_corpus","The list did not explicitly select every lifecycle status."),M(t,i.exclude_terminal===!0,"terminal_items_excluded","Terminal lifecycle states were explicitly excluded."),M(t,i.strict_read!==!0,"strict_read_unproven","The result does not echo strict source-read enforcement."),i}function zu(e,t,n){M(n,e.has_more!==!1||e.next_cursor!==null||e.truncated!==!1||e.applied_limit!==void 0||t.no_truncate!==!0,"page_incomplete","Pagination or a row ceiling may have withheld items."),M(n,e.count!==e.items.length||e.total!==e.items.length,"count_mismatch","Envelope counts do not equal the returned item count.");let o=re(e.projection)?e.projection:{};M(n,o.mode!=="full"||o.fields!==null,"projection_incomplete","The result is not the full metadata projection.");let r=re(e.omission_receipt)?e.omission_receipt:void 0;M(n,r===void 0,"omission_receipt_missing","The result carries no field-omission receipt."),M(n,r!==void 0&&(r.has_omissions!==!1||r.omitted_field_group_count!==0||!Number.isSafeInteger(r.omitted_field_group_count)||!Array.isArray(r.omitted_field_groups)||r.omitted_field_groups.length!==0),"omission_receipt_invalid","The field-omission receipt is malformed or contradicts its no-omission claim."),M(n,r?.has_omissions===!0,"field_omission","The omission receipt reports withheld field groups.")}function Hu(e){return e.contract_version!==1||e.command!=="list"||e.within_budget!==!0||e.strings_compacted!==!1||e.rows_compacted!==!1||e.result_omitted!==!1}function Bu(e){if(!Array.isArray(e.requested_dimensions))return!1;let t=new Set(e.requested_dimensions);return["include","amount","cost"].every(n=>t.has(n))}function Wu(e,t){let n=re(e.read_output)?e.read_output:void 0;M(t,n===void 0,"read_output_missing","The result carries no universal read-output receipt."),M(t,n!==void 0&&Hu(n),"read_output_invalid","The universal read-output receipt does not prove an intact list result."),M(t,n!==void 0&&!Bu(n),"read_output_dimensions_incomplete","The universal read-output receipt does not prove full, unbounded include, amount, and cost dimensions."),M(t,n?.strings_compacted===!0||n?.rows_compacted===!0||e.output_budget_truncation!==void 0,"budget_compaction","Universal output shaping compacted the result.");let o=re(e.output_budget_exceeded)?e.output_budget_exceeded:void 0;M(t,n?.result_omitted===!0||o?.omitted_result===!0,"budget_omission","Universal output shaping omitted the useful result."),M(t,e.read_session!==void 0,"session_projection","A cross-call read session can suppress previously served facts.")}function Vu(e,t){let n=e.map(o=>re(o)&&typeof o.id=="string"?o.id.trim():"");M(t,n.some(o=>o.length===0),"invalid_item_id","Every full item row must carry a non-empty string id."),M(t,new Set(n).size!==n.length,"duplicate_item_id","Every item id must occur exactly once.")}function Td(e){if(!re(e)||!Array.isArray(e.items))return{ok:!1,findings:[{code:Uu[0],message:"The result must be an object with an items array."}]};let t=e,n=[],o=qu(t,n);return zu(t,o,n),Wu(t,n),Vu(t.items,n),{ok:n.length===0,findings:n}}function Ku(e,t){return t.includeBody!==void 0?t.includeBody:re(e)&&re(e.filters)&&e.filters.include_body===!0}function eo(e,t={}){let n=Td(e);if(!n.ok)throw new Qn(n.findings,{includeBody:Ku(e,t)});let o=e;return{...o,complete_list:{contract_version:1,item_count:o.items.length,unique_item_id_count:new Set(o.items.map(r=>r.id)).size,terminal_items_included:!0,source_complete:!0,full_projection:!0,no_omissions:!0,unbounded:!0}}}function Ju(e,t={}){eo(e,t)}async function Od(e,t){let n=x(t??process.cwd(),e),o=await I(n);return Ut(n,o.item_format,F(o,null).type_to_folder,void 0,o.schema)}var Yu={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function $d(e){return Object.fromEntries(Ki.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Pr={ctx:{action:"context"},...Yu,...$d("extension"),...$d("package"),...Object.fromEntries(Ji.map(e=>[`package-${e}`,{action:e}]))};function Fd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xu(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Nr(e,t){let n=Xu(t),o=n==="brief"?n:Fd(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Fd(e.filters)?e.filters:{},projection:o}}}import{readFile as Zu}from"node:fs/promises";async function Lr(e,t){let n=e.add!==void 0,o=e.stdin===!0,r=typeof e.file=="string",i=Number(n)+Number(o)+Number(r);if(i===0)return;if(i>1)throw new p("Specify comment text using only one input source: --add, --stdin, or --file",u.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",rs(e))??"",emptyFlag:"--add"};if(o)return or(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let s=e.file.trim();if(!s)throw new p("--file path cannot be empty",u.USAGE);if(s==="-")return or(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await Zu(s,"utf8"),emptyFlag:"--file"}}catch(a){if(Cc(a)&&Je(a))throw new p(`--file path not found: ${s}. Use --file - to read stdin.`,u.USAGE);let c=a instanceof Error?a.message:String(a);throw new p(`Failed to read --file path "${s}": ${c}. Use --file - to read stdin.`,u.USAGE)}}async function Qu(e,t){let n=e.edit,o=e.delete,r=n!==void 0,i=o!==void 0;if(r&&i)throw new p("Specify only one of --edit or --delete",u.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new p("--edit must be a positive integer",u.USAGE);if(o!==void 0&&(!Number.isInteger(o)||o<1))throw new p("--delete must be a positive integer",u.USAGE);if(i){if(await Lr(e,t)!==void 0)throw new p("--delete does not take comment text",u.USAGE);return{mode:"delete",index:o}}if(r){let c=await Lr(e,t);if(c===void 0)throw new p("--edit requires replacement text via positional [text], --add, --stdin, or --file",u.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let s=await Lr(e,t);return s===void 0?{mode:"list"}:{mode:s.emptyFlag==="--add"?"add":s.emptyFlag==="--stdin"?"stdin":"file",value:s.value,emptyFlag:s.emptyFlag}}async function Pd(e,t,n){let o=pn(),r=await Qu(t,o),i=r.mode==="add"||r.mode==="edit",s=r.value??"";return it(e,t,n,{input:{...r,rawValue:t.add??s,value:i?rt(s,{stripPlainTextPrefix:!0}):s},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(r.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}function Nd(e){let t=e.options.all===!0,n=e.id??h(e.options,"id");return zl(n,t),t?Wn(e.options,e.global):Ee(n,e.options,e.global)}function Ld(e){let t=e.options.ids,n=ea(t);if(t!==void 0&&n==="")throw new p("history-compact ids requires at least one valid item ID.",u.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let o=n===void 0?void 0:Qs(n),r=Y(e.options.allOver??e.options.all_over,"history-compact allOver"),i=Y(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=h(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(s==="closed"||s==="all-streams")&&a.push(s);let c=[...new Set(a)];if(c.length>1)throw new p("history-compact: closed and all-streams scopes are mutually exclusive.",u.USAGE);let l=c[0];return Kl(e.id,{ids:o,allOver:r,scope:l}),e.id!==void 0?Vl(e.id,{before:h(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:h(e.options,"author"),message:h(e.options,"message"),force:e.force},e.global):Jl({ids:o,scope:l,allOver:r,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:h(e.options,"author"),message:h(e.options,"message"),force:e.force},e.global)}async function Md(e,t,n){return it(e,t,n,{input:await Ln(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:o=>rt(o),createEntry:o=>o,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}async function jd(e,t,n){if($c(t),Ht(e,"append","id"),t=ns(t),t.body===void 0)throw new p("Missing required --body text",u.USAGE);let o=pn(),r=x(process.cwd(),n.path);await P(r);let i=await I(r),s=C(t.author,i.author_default),c=(await o.resolveValue(t.body,"--body",is(t,"body"))).trim();if(c.length===0)throw new p("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",u.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let l=await qt({pmRoot:r,settings:i,id:e,op:"append",author:s,message:t.message,force:t.force,mutate(d){let m=d.body.trim().length>0?`
7
+ `)}return this.#e=i,Object.freeze({version_before:a,version_after:i.version,appended:Object.freeze(l),skipped_event_ids:Object.freeze(d)})}finally{await o()}}async snapshot(t={}){return this.#e=await this.#r(),this.#e.snapshot(t)}async page(t){return this.#e=await this.#r(),this.#e.page(t)}async*stream(t={}){this.#e=await this.#r(),yield*this.#e.stream(t)}async project(t,n,o={}){return this.#e=await this.#r(),this.#e.project(t,n,o)}async#r(){let t=await Yn(this.#t);try{let n=await qe(this.#t,this.#i);return(await Xn(n,this.#n,this.#o)).log}finally{await t()}}};function $r(e){let t=vn();for(let n of e)t.register(n);return t}function Gu(e,t,n=[]){if(n.length===0)return e;let o=JSON.parse(e),r=JSON.parse(Wo(t));for(let i of n){let s=i.split("."),a=r;for(let d of s){let m=$o(a);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(d)||["constructor","prototype","__proto__"].includes(d)||m===null||!Object.hasOwn(m,d))throw new p(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,u.USAGE);a=m[d]}if($o(a)===null)throw new p(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,u.USAGE);let c=o,l=r;for(let d of s.slice(0,-1)){let m=c[d];l=l[d],m===void 0&&Object.defineProperty(c,d,{value:structuredClone(l),enumerable:!0,writable:!0,configurable:!0}),c=c[d]}Object.defineProperty(c,s.at(-1),{value:a,enumerable:!0,writable:!0,configurable:!0})}return J(o,JSON.parse(e))?e:`${JSON.stringify(o,null,2)}
8
+ `}function Cd(e,t,n){let o=new Map;for(let r of[...t,...n]){let i=e(r);i!==void 0&&o.set(i.key,i)}return o}function Uu(e,t){return[...t].filter(([n,o])=>!J(e.get(n),o)).map(([,n])=>n)}async function qu(e,t,n,o){let r=t.schema?.fields??[],{normalizeCliToken:i,resolveRuntimeFieldRegistry:s}=await import("./runtime-schema-3RAXYNG5.js"),a=g=>s({fields:[g]}).definitions[0],c=g=>JSON.parse(JSON.stringify(g)),l=[...e.schema.fields,...Array.isArray(n)?n:[]].map(g=>({resolved:a(g),persisted:c(g)})),d=g=>[g.cli_flag,...Array.isArray(g.cli_aliases)?g.cli_aliases:[]].some(y=>typeof y=="string"&&i(y).length===0),m=r.filter(g=>{let y=a(g),k=l.some(b=>J(b.persisted,c(g)));return y===void 0||d(g)?!k:!l.some(b=>J(b.resolved,y))});if(m.push(...Uu(Cd(a,e.schema.fields,o.before),Cd(a,o.inlineAfter,o.after))),m.length===0)return;let{assertFieldDefinitionOptionsAvailable:f}=await import("./field-option-collisions-G4LQ2646.js");for(let g of m)f(g)}function Rd(e,t,n,o){return{fitOutputEnvelope:Ad,client:t,isItemNotFoundError:r=>Zo(r)&&r.exitCode===u.NOT_FOUND,getItemAt:(r,i)=>Da(r,i,{pmRoot:e}),readSettingsSection:(r,i)=>Na(e,r,i),writeSettingsSection:(r,i,s)=>La(e,r,i,{author:n,...s}),openRelationshipEventStore:r=>Zn.open({pmRoot:e,nodes:r.nodes,registry:$r(r.definitions),...r.relativePath===void 0?{}:{relativePath:r.relativePath}}),createRelationshipGraph:r=>new et(r.nodes,r.edges,$r(r.definitions)),analyzeRelationshipImpact:(r,i,s)=>ja(r,i,s),validateRelationshipEvents:r=>{let i=new Zt(r.nodes,{registry:$r(r.definitions)});return r.events.map(s=>i.append({...s,expectedVersion:i.version}))},commitWorkspaceTransaction:r=>Ga({...r,pmRoot:e}),mutateWorkspaceSettings:async r=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(r.operationId))throw new p("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",u.USAGE);let i=r.dryRun===!0?await nt(e,()=>I(e)):await I(e);try{let s=await oa({pmRoot:e,filePath:Se(e),op:"extension:pm:settings",idempotencyKey:o===void 0?r.operationId:`${ju("sha256").update(o).digest("hex").slice(0,16)}:${r.operationId}`,author:C(n,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:r.dryRun===!0,mutate:async a=>{let c=a===null?null:JSON.parse(a),l=Cn(c);if(!l.success)throw new p("Workspace settings mutation requires a valid initialized settings.json.",u.USAGE);let d=Bo(l.data),m=await r.mutate(structuredClone(d));if(!Cn(m).success)throw new p("Workspace settings mutation returned invalid settings.json.",u.USAGE);let f=J(d,m)?a:Wo(m,{source:{raw:c,validated:l.data}});f=Gu(f,m,r.replaceSubtrees);let g=Cn(JSON.parse(f));if(!g.success)throw new p("Workspace settings mutation serialized invalid settings.json.",u.USAGE);let y=g.data.schema,{readFieldsFileDefinitions:k}=await import("./field-definition-losses-JFMMMVTV.js");return await qu(d,m,c.schema?.fields,{before:await k(e,d.schema),after:await k(e,y),inlineAfter:y?.fields??[]}),{raw:f,result:r.includePreview===!0?Bo(g.data):void 0}}});return s.changed&&r.dryRun!==!0&&await G({path:Se(e),scope:"project",op:"extension:pm:settings"}),{changed:s.changed,dry_run:r.dryRun===!0,replayed:s.replayed===!0,...s.result===void 0?{}:{preview:s.result}}}finally{la(e)}}}}function Td(e){return{undeclaredKeys:Jc(e)?"pass":"refuse"}}var zu=["invalid_envelope","source_incomplete","source_unchecked","filtered_corpus","terminal_items_excluded","strict_read_unproven","page_incomplete","count_mismatch","projection_incomplete","field_omission","omission_receipt_missing","omission_receipt_invalid","read_output_missing","read_output_invalid","read_output_dimensions_incomplete","budget_compaction","budget_omission","session_projection","invalid_item_id","duplicate_item_id"],Qn=class extends Error{receipt;constructor(t,n={}){super(`Complete-list certification failed: ${t.map(r=>r.code).join(", ")}.`),this.name="PmCompleteListValidationError";let o=n.includeBody===!0;this.receipt={contract_version:1,contract:"complete_list",findings:t,recovery:{suggested_retry:`pm list --all --output-include full --strict-read --no-truncate --output-budget unbounded --output-limit unbounded${o?" --include-body":""} --json`,sdk:o?"await client.listAllComplete({ includeBody: true })":"await client.listAllComplete()"}}}};function Fr(e={}){return Ts({excludeTerminal:!1,full:!0,...e.includeBody===void 0?{}:{includeBody:e.includeBody},noTruncate:!0,outputBudget:"unbounded",outputLimit:"unbounded",strictRead:!0},["full"])}function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,t,n,o){t&&e.push({code:n,message:o})}function Hu(e,t){let n=re(e.completeness)?e.completeness:{};M(t,n.status==="partial","source_incomplete","The source scan reported unreadable tracker artifacts."),M(t,n.status!=="complete"&&n.status!=="partial","source_unchecked","The source scan did not prove completeness.");let o=n.unreadable_item_count,r=n.unreadable_directory_count;M(t,n.status==="complete"&&(o!==0||r!==0)&&Number.isSafeInteger(o)&&Number.isSafeInteger(r),"source_incomplete","The source scan reports unreadable tracker artifacts despite a complete status."),M(t,n.status==="complete"&&(!Number.isSafeInteger(o)||!Number.isSafeInteger(r)||Number(o)<0||Number(r)<0),"source_unchecked","The source scan did not report safe non-negative unreadable counts.");let i=re(e.filters)?e.filters:{},s=re(i.runtime_filters)?i.runtime_filters:{},a=new Set(["exclude_terminal","include_body","no_truncate","runtime_filters","status","strict_read"]);return M(t,i.status!=="all"||Object.keys(s).length>0||Object.keys(i).some(c=>!a.has(c)),"filtered_corpus","The list did not explicitly select every lifecycle status."),M(t,i.exclude_terminal===!0,"terminal_items_excluded","Terminal lifecycle states were explicitly excluded."),M(t,i.strict_read!==!0,"strict_read_unproven","The result does not echo strict source-read enforcement."),i}function Bu(e,t,n){M(n,e.has_more!==!1||e.next_cursor!==null||e.truncated!==!1||e.applied_limit!==void 0||t.no_truncate!==!0,"page_incomplete","Pagination or a row ceiling may have withheld items."),M(n,e.count!==e.items.length||e.total!==e.items.length,"count_mismatch","Envelope counts do not equal the returned item count.");let o=re(e.projection)?e.projection:{};M(n,o.mode!=="full"||o.fields!==null,"projection_incomplete","The result is not the full metadata projection.");let r=re(e.omission_receipt)?e.omission_receipt:void 0;M(n,r===void 0,"omission_receipt_missing","The result carries no field-omission receipt."),M(n,r!==void 0&&(r.has_omissions!==!1||r.omitted_field_group_count!==0||!Number.isSafeInteger(r.omitted_field_group_count)||!Array.isArray(r.omitted_field_groups)||r.omitted_field_groups.length!==0),"omission_receipt_invalid","The field-omission receipt is malformed or contradicts its no-omission claim."),M(n,r?.has_omissions===!0,"field_omission","The omission receipt reports withheld field groups.")}function Wu(e){return e.contract_version!==1||e.command!=="list"||e.within_budget!==!0||e.strings_compacted!==!1||e.rows_compacted!==!1||e.result_omitted!==!1}function Vu(e){if(!Array.isArray(e.requested_dimensions))return!1;let t=new Set(e.requested_dimensions);return["include","amount","cost"].every(n=>t.has(n))}function Ku(e,t){let n=re(e.read_output)?e.read_output:void 0;M(t,n===void 0,"read_output_missing","The result carries no universal read-output receipt."),M(t,n!==void 0&&Wu(n),"read_output_invalid","The universal read-output receipt does not prove an intact list result."),M(t,n!==void 0&&!Vu(n),"read_output_dimensions_incomplete","The universal read-output receipt does not prove full, unbounded include, amount, and cost dimensions."),M(t,n?.strings_compacted===!0||n?.rows_compacted===!0||e.output_budget_truncation!==void 0,"budget_compaction","Universal output shaping compacted the result.");let o=re(e.output_budget_exceeded)?e.output_budget_exceeded:void 0;M(t,n?.result_omitted===!0||o?.omitted_result===!0,"budget_omission","Universal output shaping omitted the useful result."),M(t,e.read_session!==void 0,"session_projection","A cross-call read session can suppress previously served facts.")}function Ju(e,t){let n=e.map(o=>re(o)&&typeof o.id=="string"?o.id.trim():"");M(t,n.some(o=>o.length===0),"invalid_item_id","Every full item row must carry a non-empty string id."),M(t,new Set(n).size!==n.length,"duplicate_item_id","Every item id must occur exactly once.")}function Od(e){if(!re(e)||!Array.isArray(e.items))return{ok:!1,findings:[{code:zu[0],message:"The result must be an object with an items array."}]};let t=e,n=[],o=Hu(t,n);return Bu(t,o,n),Ku(t,n),Ju(t.items,n),{ok:n.length===0,findings:n}}function Yu(e,t){return t.includeBody!==void 0?t.includeBody:re(e)&&re(e.filters)&&e.filters.include_body===!0}function eo(e,t={}){let n=Od(e);if(!n.ok)throw new Qn(n.findings,{includeBody:Yu(e,t)});let o=e;return{...o,complete_list:{contract_version:1,item_count:o.items.length,unique_item_id_count:new Set(o.items.map(r=>r.id)).size,terminal_items_included:!0,source_complete:!0,full_projection:!0,no_omissions:!0,unbounded:!0}}}function Xu(e,t={}){eo(e,t)}async function $d(e,t){let n=x(t??process.cwd(),e),o=await I(n);return Ut(n,o.item_format,F(o,null).type_to_folder,void 0,o.schema)}var Zu={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function Fd(e){return Object.fromEntries(Ki.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Pr={ctx:{action:"context"},...Zu,...Fd("extension"),...Fd("package"),...Object.fromEntries(Ji.map(e=>[`package-${e}`,{action:e}]))};function Pd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qu(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Nr(e,t){let n=Qu(t),o=n==="brief"?n:Pd(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Pd(e.filters)?e.filters:{},projection:o}}}import{readFile as ef}from"node:fs/promises";async function Lr(e,t){let n=e.add!==void 0,o=e.stdin===!0,r=typeof e.file=="string",i=Number(n)+Number(o)+Number(r);if(i===0)return;if(i>1)throw new p("Specify comment text using only one input source: --add, --stdin, or --file",u.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",rs(e))??"",emptyFlag:"--add"};if(o)return or(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let s=e.file.trim();if(!s)throw new p("--file path cannot be empty",u.USAGE);if(s==="-")return or(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await ef(s,"utf8"),emptyFlag:"--file"}}catch(a){if(Cc(a)&&Je(a))throw new p(`--file path not found: ${s}. Use --file - to read stdin.`,u.USAGE);let c=a instanceof Error?a.message:String(a);throw new p(`Failed to read --file path "${s}": ${c}. Use --file - to read stdin.`,u.USAGE)}}async function tf(e,t){let n=e.edit,o=e.delete,r=n!==void 0,i=o!==void 0;if(r&&i)throw new p("Specify only one of --edit or --delete",u.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new p("--edit must be a positive integer",u.USAGE);if(o!==void 0&&(!Number.isInteger(o)||o<1))throw new p("--delete must be a positive integer",u.USAGE);if(i){if(await Lr(e,t)!==void 0)throw new p("--delete does not take comment text",u.USAGE);return{mode:"delete",index:o}}if(r){let c=await Lr(e,t);if(c===void 0)throw new p("--edit requires replacement text via positional [text], --add, --stdin, or --file",u.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let s=await Lr(e,t);return s===void 0?{mode:"list"}:{mode:s.emptyFlag==="--add"?"add":s.emptyFlag==="--stdin"?"stdin":"file",value:s.value,emptyFlag:s.emptyFlag}}async function Nd(e,t,n){let o=pn(),r=await tf(t,o),i=r.mode==="add"||r.mode==="edit",s=r.value??"";return it(e,t,n,{input:{...r,rawValue:t.add??s,value:i?rt(s,{stripPlainTextPrefix:!0}):s},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(r.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}function Ld(e){let t=e.options.all===!0,n=e.id??h(e.options,"id");return zl(n,t),t?Wn(e.options,e.global):Ee(n,e.options,e.global)}function Md(e){let t=e.options.ids,n=na(t);if(t!==void 0&&n==="")throw new p("history-compact ids requires at least one valid item ID.",u.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let o=n===void 0?void 0:ta(n),r=X(e.options.allOver??e.options.all_over,"history-compact allOver"),i=X(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=h(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(s==="closed"||s==="all-streams")&&a.push(s);let c=[...new Set(a)];if(c.length>1)throw new p("history-compact: closed and all-streams scopes are mutually exclusive.",u.USAGE);let l=c[0];return Kl(e.id,{ids:o,allOver:r,scope:l}),e.id!==void 0?Vl(e.id,{before:h(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:h(e.options,"author"),message:h(e.options,"message"),force:e.force},e.global):Jl({ids:o,scope:l,allOver:r,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:h(e.options,"author"),message:h(e.options,"message"),force:e.force},e.global)}async function Dd(e,t,n){return it(e,t,n,{input:await Ln(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:o=>rt(o),createEntry:o=>o,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}async function Gd(e,t,n){if($c(t),Ht(e,"append","id"),t=ns(t),t.body===void 0)throw new p("Missing required --body text",u.USAGE);let o=pn(),r=x(process.cwd(),n.path);await P(r);let i=await I(r),s=C(t.author,i.author_default),c=(await o.resolveValue(t.body,"--body",is(t,"body"))).trim();if(c.length===0)throw new p("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",u.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let l=await qt({pmRoot:r,settings:i,id:e,op:"append",author:s,message:t.message,force:t.force,mutate(d){let m=d.body.trim().length>0?`
9
9
 
10
10
  `:"";return d.body=`${d.body.trimEnd()}${m}${c}
11
- `,{changedFields:["body"]}}});return{item:l.item,appended:c,changed_fields:l.changedFields}}function ef(e,t,n){let o={...t.metadata,body:t.body},r={...n.metadata,body:n.body};for(let i of new Set([...Object.keys(o),...Object.keys(r)])){if(i==="updated_at"||i==="pm_format_version")continue;let s=o[i],a=r[i];if(ee(s,a))continue;let c=e.get(i);if(c&&!ee(c.after,s))throw new p(`Rollback conflict on ${i}: the batch effects contain an intervening edit. Inspect pm history before resolving it.`,u.CONFLICT);e.set(i,{field:i,before:c?c.before:s,after:a})}}function tf(e,t,n){let o=new Map;for(let[r,i]of e.entries()){if(i.context?.bulk_checkpoint!==t)continue;let s=Po(Vo(e,r-1),{schema:n}),a=Po(Vo(e,r),{schema:n});ef(o,s,a)}return[...o.values()].filter(r=>!ee(r.before,r.after))}function nf(e,t){let n={...e.metadata,body:e.body},o=t.filter(r=>!ee(n[r.field],r.after));if(o.length>0)throw new p(`Rollback conflict on ${o.map(r=>r.field).join(", ")}: a later edit changed a batch field. Inspect pm get/history and reconcile it explicitly before retrying.`,u.CONFLICT);for(let r of t)r.field==="body"?e.body=r.before:r.before===void 0?delete e.metadata[r.field]:e.metadata[r.field]=structuredClone(r.before);return t.map(r=>r.field)}async function to(e,t,n){if(t.record.rollback_strategy!=="guarded_inverse")throw new p("This legacy checkpoint has no attributable inverse effects. Inspect pm history and use an explicit pm restore only after reviewing later edits.",u.CONFLICT);let o=await I(e),r=new Map,i=await fs(t.items,async a=>{try{return await of(e,o,t,a,n)}catch(c){throw r.set(a,c),c}}),s=[];for(let a of i.rows)s.push(a.status==="failed"?{...a,...await ot(r.get(a.id),e)}:a);return{...i,rows:s}}async function of(e,t,n,o,r){let i=await ga({pmRoot:e,settings:t,id:o,op:"restore",author:C(r.author,t.author_default),message:r.message,force:r.force,skipNoop:!0,historyContext:{bulk_rollback:n.id},async mutate(s){let a=await Is(me(e,o),o);if(!Na(a,s).ok)throw new p(`Cannot safely roll back ${o}: item/history verification failed. Inspect pm history --verify before recovery.`,u.CONFLICT);return a.some(l=>l.context?.bulk_rollback===n.id)?{changedFields:[]}:{changedFields:nf(s,tf(a,n.id,t.schema))}}});return{changed_fields:i.changedFields,warnings:i.warnings,skipped:i.changedFields.length===0}}var Ud=2,Mr="close-many",rf=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function sf(e,t){return Jt(e,t,{includePagination:!1})}function af(e,t){return Jt(e,t)}function cf(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)}function lf(e){let t={};if(!e)return t;for(let[n,o]of Object.entries(e))o==null||typeof o=="string"&&!o.split(",").some(r=>r.trim().length>0)||(t[n]=o);return t}function df(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new p("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",u.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function mf(e,t){let n=W(t.schema),o=F(t,T()),r=await Ut(e,t.item_format,o.type_to_folder,void 0,t.schema),i=new Map,s=new Map;for(let a of r){if(typeof a.parent!="string"||a.parent.length===0||(s.set(a.id,a.parent),Ze(a.status,n)))continue;let c=i.get(a.parent);c?c.push(a.id):i.set(a.parent,[a.id])}for(let a of i.values())a.sort((c,l)=>c.localeCompare(l));return{childrenByParent:i,parentByChild:s}}function Gd(e,t,n){let o=n?.get(e);if(o!==void 0)return o;let r=0,i=t.get(e),s=[],a=new Set,c=!1;for(;i!==void 0&&!a.has(i);){let l=n?.get(i);if(l!==void 0){r+=l+1;break}a.add(i),s.push(i),r+=1,i=t.get(i)}if(i!==void 0&&a.has(i)&&(c=!0),!c){n?.set(e,r);for(let[l,d]of s.entries())n?.set(d,r-l-1)}return r}async function pf(e){let t=await yn(e.pmRoot,Mr,e.rollbackId,Ud),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,o=await to(e.pmRoot,t,{author:e.options.author,message:n,force:e.options.force}),r=o.rows.filter(i=>i.status==="skipped").length;return{...je({applied:o.restored_ids.length,skipped:r,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:o.restored_ids.length,skipped_count:r,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}}function uf(e,t,n,o,r){return e.map(i=>{let s=(t.get(i.id)??[]).filter(c=>!n.has(c)),a=!qd(i,o,r);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...s.length>0?{active_child_ids:s}:{}}})}async function ff(e){let t=await gn(e.pmRoot,Mr,e.checkpointId,{schema_version:Ud,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function _f(e){let t=[],n=[];for(let o of e.matched){if(!e.closableIds.has(o.id)){t.push({id:o.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let r=await Rn({pmRoot:e.pmRoot,itemId:o.id,checkpointId:e.checkpointId},()=>Kt(o.id,e.reason,e.closeOptions,e.global));t.push({id:o.id,status:"closed",completion:r.completion,changed_fields:r.changed_fields,...r.warnings&&r.warnings.length>0?{warnings:r.warnings}:{}}),n.push(o.id)}catch(r){let i=await Kn(r,o.id,e.pmRoot);if(i!==void 0){t.push({id:o.id,status:"closed",...i}),n.push(o.id);continue}t.push({id:o.id,status:"failed",error:Ae(r),...await ot(r,e.pmRoot)})}}return{rows:t,closedIds:n}}function hf(e){return _n(e.rollback)}function gf(e){if(e.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(af(e.list,e.status))throw new p("Rollback mode does not accept filter options",u.USAGE)}function yf(e){if(!sf(e.list,e.status))throw new p(`close-many requires at least one filter to scope the close (for example: ${rf}). Refusing to match every item.`,u.USAGE)}function bf(e,t){let n=new Map;return[...e].sort((o,r)=>{let i=Gd(r.id,t,n)-Gd(o.id,t,n);return i!==0?i:o.id.localeCompare(r.id)})}function qd(e,t,n){return n||!Ze(e.status,t)}function wf(e,t,n){return new Set(e.filter(o=>qd(o,t,n)).map(o=>o.id))}async function vf(e){yf(e.options);let t=W(e.settings.schema),n=df(e.options.reason,e.settings.governance.require_close_reason),o=e.options.force===!0,r=await _e(e.options.status,lf(e.options.list),e.global),{childrenByParent:i,parentByChild:s}=await mf(e.pmRoot,e.settings),a=bf(r.items,s),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],l=c.length===0?[]:(await _e(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,d=new Set(l.map(f=>f.id)),m=wf(a,t,o);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:o,listed:r,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!d.has(f)),planRows:uf(a,i,m,t,o)}}function kf(e){return{outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function Sf(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return ff({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function zd(e,t){let n=hf(e),o=x(process.cwd(),t.path);await P(o);let r=await I(o),i=e.dryRun===!0;if(cf(e.list),n!==void 0)return gf(e),pf({pmRoot:o,rollbackId:n,options:e,global:t});let s=await vf({pmRoot:o,settings:r,options:e,global:t});if(i)return kf(s);let a=new Set(s.planRows.filter(v=>v.action==="close").map(v=>v.id)),c=S(),l=hn(Mr,c),d=await Sf({context:s,options:e,closableIds:a,checkpointId:l,nowValue:c}),m={author:e.author,message:e.message??`close-many apply ${l}`,completedAt:e.completedAt,validateClose:s.validateCloseMode,force:s.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:g}=await _f({pmRoot:o,checkpointId:l,matched:s.matched,closableIds:a,reason:s.reason,closeOptions:m,global:t}),y=f.filter(v=>v.status==="closed").length,k=f.filter(v=>v.status==="skipped").length,b=f.filter(v=>v.status==="failed").length;return{...je({applied:y,skipped:k,failed:b,unmatched:s.unmatchedIds?.length??0}),mode:"apply",matched_count:s.matched.length,dry_run:!1,...s.reason!==void 0?{reason:s.reason}:{},filters:s.listed.filters,...s.validateCloseMode?{validate_close:s.validateCloseMode}:{},...d?{checkpoint:d}:{},closed_count:y,skipped_count:k,failed_count:b,rows:f,ids:g,...s.unmatchedIds!==void 0?{unmatched_ids:s.unmatchedIds,unmatched_count:s.unmatchedIds.length}:{}}}function Af(e,t){return[...new Set([...Wi.filter(o=>e[o]!==void 0),...Object.keys(e).filter(o=>e[o]!==void 0),...t.length>0?["body"]:[]])].sort((o,r)=>o.localeCompare(r))}function xf(e,t){let n=`copied_from=${e}`;if(!t)return n;let o=t.trim();return o.length>0?`${o} | ${n}`:n}async function Dr(e,t,n){let o=x(process.cwd(),n.path);await P(o);let r=await I(o),i=F(r,T()),s=await oe(o,e,r.id_prefix,r.item_format,i.type_to_folder);if(!s)throw await On(o,e,r.id_prefix,i.type_to_folder);let a=await xe(s,{schema:r.schema}),c=a.document.metadata,l=S(),d=C(t.author,r.author_default),m=await Ho(o,r.id_prefix,{tokenLength:r.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=W(r.schema),g=t.title?.trim();if(g!==void 0&&g.length===0)throw new p("Copy --title must not be empty",u.USAGE);let y={...c,id:m,title:g??c.title,status:f.open_status,created_at:l,updated_at:l};delete y.closed_at,delete y.completed_at,delete y.close_reason,delete y.test_runs;let k=pe(T()),b=Mt({metadata:y,body:a.document.body},{schema:r.schema,extensionFieldNames:k}),v=await cr({title:b.metadata.title,description:b.metadata.description,body:b.body,excludeIds:[s.id]},{pmRoot:o,mode:r.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":r.governance.duplicate_detection_mode,threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),_=Af(b.metadata,b.body),A=Oo(o,b.metadata.type,m,r.item_format,i.type_to_folder),N=me(o,m),O=await Dt(o,m,r.locks.ttl_seconds,d,!1,r.governance.force_required_for_stale_lock,r.locks.wait_ms),B={metadata:{},body:""},$,R,ie;try{let Tt=await ua(o,d,{required:r.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{r.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await cr({title:b.metadata.title,description:b.metadata.description,body:b.body,excludeIds:[s.id]},{pmRoot:o,mode:"strict",threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:!1});let ne=await oe(o,m,r.id_prefix,r.item_format,i.type_to_folder);if(ne)throw new p(`Cannot copy to ${m}: an item with that id already exists at ${ne.itemPath}. Retry the copy to allocate a new id.`,u.CONFLICT,{code:"item_id_collision",why:`Allocated id ${m} already exists at ${ne.itemPath}.`,recovery:{suggested_retry:`pm copy ${s.id}`}});let Ve=await Cn({pmRoot:o,settings:r,operation:"create",author:d,before:null,after:b});ie=Ve.warnings,await An({pm_root:o,operation:"create",before:null,after:b,changed_fields:_,author:d,sdk:Tn({pmRoot:o,settings:r,typeToFolder:i.type_to_folder})}),await O.fence(async()=>{await se(A,Lt(b,{format:r.item_format,schema:r.schema,extensionFieldNames:k}));try{let Ke=jt({nowIso:l,author:d,op:"create",before:B,after:b,message:xf(s.id,t.message),context:Ve.decisions.length===0?void 0:{workflow_policies:Ve.decisions}});await Gt(N,Ke)}catch(Ke){throw await Ft(A),Ke}}),R=await fa({pmRoot:o,preferredFormat:r.item_format,typeToFolder:i.type_to_folder,schema:r.schema,itemPath:A,document:b})}finally{await Tt()}$=[...await G({path:A,scope:"project",op:"create",item_id:b.metadata.id,item_type:b.metadata.type,before:B,after:b,changed_fields:_}),...await G({path:N,scope:"project",op:"create:history",item_id:b.metadata.id,item_type:b.metadata.type,before:B,after:b,changed_fields:_})],Ws({id:b.metadata.id,op:"create",item_type:b.metadata.type,status:b.metadata.status,current:Vs(b.metadata,_),changed_fields:_})}finally{await O.release()}return{source_id:s.id,item:structuredClone(b.metadata),changed_fields:_,warnings:[...xl(v),...ie,...R,...$],...v===void 0?{}:{similarity_advisory:v}}}import no from"node:path";async function jr(e,t,n){let o=x(process.cwd(),n.path);await P(o);let r=await I(o),i=C(t.author,r.author_default),s=await ya({pmRoot:o,settings:r,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),a=s.targetPath?no.relative(o,s.targetPath).split(no.sep).join("/"):void 0;return{item:s.item,changed_fields:s.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:s.item.status,...a?{target_path:a}:{},history_retained:no.relative(o,me(o,s.item.id)).split(no.sep).join("/"),tombstone_retention:"retain_append_only",warnings:s.warnings}}async function If(e){await P(e)}async function Gr(e,t,n){let o=x(process.cwd(),n.path);if(await If(o),t.clear===!0){if(e!==void 0)throw new p("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",u.USAGE);let m=await I(o),f=Fo(C(void 0,m.author_default));return await xs(o),await ur({pmRoot:o,settings:m,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let m=await Ss(o);if(m===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await Ef(o,m);return{action:"show",focused_item:m,title:f,message:`Focused on ${m}${f?` (${f})`:""}. New items default --parent to it.`}}let i=await I(o),s=F(i,T()),a=await oe(o,e,i.id_prefix,i.item_format,s.type_to_folder);if(!a)throw await On(o,e,i.id_prefix,s.type_to_folder);let c=zo(a.id,i.id_prefix),l=await xe(a,{schema:i.schema}),d=Hd(l.document.metadata.title);return await As(o,c),await ur({pmRoot:o,settings:i,principal:Fo(C(void 0,i.author_default)),itemId:c}),{action:"set",focused_item:c,title:d,message:`Focused on ${c}${d?` (${d})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function Ef(e,t){let n=await I(e),o=F(n,T()),r=await oe(e,t,n.id_prefix,n.item_format,o.type_to_folder);if(!r)return null;let i=await xe(r,{schema:n.schema});return Hd(i.document.metadata.title)}function Hd(e){return e.trim().length>0?e:null}async function Ur(e,t,n,o){Ht(e,"reopen","id"),Ht(t,"reopen","reason"),Fc(n);let r=t.trim();if(r.length===0)throw new p("pm item reopen requires a non-empty recurrence reason.",u.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=x(process.cwd(),o.path),s=n.expectedResult?.trim();if(s!==void 0&&s.length===0)throw new p("Reopen expected result must describe the current active outcome.",u.USAGE);let a=W((await I(i)).schema),c=a.open_status,l=Zl(a),d=n.status??c,m=Ne(d,a)??d;if(m!==c&&m!==l)throw new p(`Reopen target status must be ${c} or ${l}; received ${d}.`,u.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([c,l])],suggested_retry:`pm item reopen ${e} "${r}" --status ${c}`,suggested_retry_args:["item","reopen",e,r,"--status",c]}});let f=await td(e,{status:m,expectedResult:s,unset:["close-reason","resolution",...s===void 0?["expected-result"]:[],"actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},o,r);return{item:f.item,changed_fields:f.changed_fields,warnings:f.warnings,recurrence:f.lifecycle_transition,...s===void 0?{recovery:{missing:["expected_result"],suggested_retry_args:["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"],suggested_retry:fn(["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"])}}:{}}}async function Bd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r=e.force===!0||o.force===!0,i={...e.args,...o},s=o.next===!0,a=e.id??h(o,"id");if(i.start===!0){if(a)return ze(e,"start_task");id(a,s,!0)}let c=s?await sd(r,e.global,i,i):await rd(Qt(e,o),r,e.global,i);return H(c,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Qt(e,t){let n=e.id??h(t,"id");if(!n)throw new p("Missing required argument: id",64);return n}function qr(e,t){return h(e.args,"reason")??h(e.args,"text")??h(t,"reason")??h(t,"text")}async function Wd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return o.releaseAssignment===!0?ze(e,"close_task"):H(await Kt(Qt(e,o),qr(e,o),{...o,force:e.force===!0||o.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function ze(e,t){let{changedFields:n,idOnly:o,runnerOptions:r}=j(e.args,e.options),i=Qt(e,r),s=st(r,{force:e.force===!0||r.force===!0}),a=t==="start_task"?await yr(i,s,e.global):t==="pause_task"?await br(i,s,e.global):await wr(i,qr(e,r),s,e.global);return H(a,{changedFields:n,idOnly:o,compactEnvelope:n==="compact"&&!o})}async function Vd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r=st(o,{message:h(Object.hasOwn(o,"message")?o:e.args,"message")});if(r.pause===!0)return ze({...e,options:r},"pause_task");let i=await ad(Qt(e,r),e.force===!0||r.force===!0,e.global,r);return H(i,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function Kd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await Ur(Qt(e,o),qr(e,o)??"",{...o,force:e.force===!0||o.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function oo(e,t){let n=fn(["plan","show",e.plan.id,"--depth","deep",...t===void 0?[]:["--pm-path",t]]);return{kind:"plan_mutation",action:e.action,id:e.plan.id,status:e.plan.status,mode:e.plan.mode,steps_summary:e.plan.steps_summary,...e.step===void 0?{}:{step:{id:e.step.id,order:e.step.order,status:e.step.status}},materialized_count:e.materialized?.length??0,skipped_count:e.materialize_skipped?.length??0,warning_count:e.warnings.length,warnings:e.warnings.slice(0,3).map(o=>o.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(o=>o.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${as(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}var Cf=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"];var Xd="plan-step-",Kr="draft",Vr=["bug-investigation","feature-implementation","refactoring-sprint"],Jd={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function Rf(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Jd,t)?Jd[t]:void 0;if(!n)throw new p(`Unknown plan template "${e}". Allowed: ${Vr.join(", ")}`,u.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Vr[0]}`]});return n.map(o=>({...o}))}function Tf(e,t){return t>0?Math.round(e/t*100):0}function Zd(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function te(e){return Array.isArray(e)?e.flatMap(t=>Qo(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Qo(e,{unique:!1}):[]}function V(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function Qd(e,t=Kr){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Eo.find(r=>r===n);if(!o)throw new p(`Invalid plan mode "${e}". Allowed: ${Eo.join(", ")}`,u.USAGE);return o}function Jr(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Co.find(r=>r===n);if(!o)throw new p(`Invalid step status "${e}". Allowed: ${Co.join(", ")}`,u.USAGE);return o}function em(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=To.find(r=>r===n);if(!o)throw new p(`Invalid step link kind "${e}". Allowed: ${To.join(", ")}`,u.USAGE);return o}function Of(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ro.find(o=>o===t);if(!n)throw new p(`Invalid plan harness "${e}". Allowed: ${Ro.join(", ")}`,u.USAGE);return n}function $f(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=tr.find(o=>o===t);if(!n)throw new p(`Invalid --depth "${e}". Allowed: ${tr.join(", ")}`,u.USAGE);return n}function Ff(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new p("Plan --fields requires a comma-separated list of plan field names",u.USAGE);return t}var zr=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function Pf(e,t){let n=e,o={},r=[];for(let i of t){let s=i.startsWith("plan.")?i.slice(5):i;if(s.length!==0){if(!zr.has(s)){r.push(i);continue}Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])}}if(r.length>0)throw new p(`Unknown Plan --fields value(s): ${r.join(", ")}`,u.USAGE,{nextSteps:[`Use --fields ${[...zr].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:r,suggested_retry:`pm plan show <id> --fields ${[...zr].join(",")}`}});return o}function Yr(e,t){let n={};for(let o of e.split(",")){let r=o.trim();if(r.length===0)continue;let i=r.indexOf("=");if(i<=0)throw new p(`Invalid ${t} entry "${r}"; expected key=value`,u.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[r.slice(0,i).trim().toLowerCase()]=r.slice(i+1).trim()}return n}function Xr(e){let t=Yr(e,"--file");if(!t.path)throw new p("--file requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Zr(e){let t=Yr(e,"--test");if(!t.command&&!t.path)throw new p("--test requires at least command=<value> or path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function Qr(e){let t=Yr(e,"--doc");if(!t.path)throw new p("--doc requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Nf(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=Tf(t.completed,t.total),t}function Lf(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let o=`${Xd}${String(n).padStart(3,"0")}`;if(!t.has(o))return o}throw new p("Could not allocate step id (limit reached)",u.GENERIC_FAILURE)}function dt(e,t){let n=t.trim();if(n.length===0)throw new p("Step reference cannot be empty",u.USAGE);let o=e.find(r=>r.id===n);if(o)return o;if(/^\d+$/.test(n)){let r=Number.parseInt(n,10),i=e.find(s=>s.order===r);if(i)return i}throw new p(`Step "${t}" not found in plan`,u.NOT_FOUND)}function Yd(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function Mf(e,t){let n=t.filter(s=>s.trim().toLowerCase()==="all"),o=[],r=[];if(n.length>0){if(t.length>n.length)throw new p("pm plan materialize --steps all cannot be combined with other step refs",u.USAGE);for(let s of e.slice().sort((a,c)=>a.order-c.order)){let a=Yd(s);if(a){r.push({from_step:s.id,...a});continue}o.push(s)}return{targets:o,skipped:r}}let i=new Set;for(let s of t){let a=dt(e,s);if(i.has(a.id))continue;i.add(a.id);let c=Yd(a);if(c){r.push({from_step:a.id,...c});continue}o.push(a)}return{targets:o,skipped:r}}function Df(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,o=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||o?.trim()||void 0}function jf(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function Gf(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function X(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((s,a)=>s.order-a.order),o=Nf(n),r=jf(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Kr,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:o,current_step:r?{id:r.id,order:r.order,title:r.title,status:r.status}:void 0,blocked_steps:Gf(n),linked_items:(e.dependencies??[]).map(s=>({id:s.id,kind:s.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function Z(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!er(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function tm(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new p(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,u.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function Uf(e){let t=x(process.cwd(),e.path);await P(t);let n=await I(t);return{pmRoot:t,settings:n}}async function nm(e,t){let n=F(e.settings,T()),o=await oe(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!o)throw new p(`Plan ${t} not found`,u.NOT_FOUND);let r=await xe(o,{schema:e.settings.schema});return tm(r.document.metadata),{document:r.document,itemId:o.id}}function qf(e){let t=[];for(let n of te(e.related))t.push(`id=${n},kind=related`);for(let n of te(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of te(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function zf(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),o=e.validationExpected?.trim();if(!(!t&&!n&&!o))return{text:t||n||"Validation check",command:n||void 0,expected:o||void 0}}function Hf(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||te(e.dependsOn).length>0||te(e.link).length>0}function Bf(e){let t=e.stepTitle?.trim()||void 0,n=Zd(e.step),o=e.template?.trim()?Rf(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...o.map(r=>r.title)],templateSteps:o}}function Wf(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new p("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",u.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Vr[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new p("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",u.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function Vf(e,t){let n=Jr(e.stepStatus,"pending"),o=ei(e,"depends_on"),r=V(e.file).map(Xr),i=V(e.test).map(Zr),s=V(e.doc).map(Qr),a=S();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:ti(e.stepOwner),evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:r.length>0?r:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function Kf(e){let t=Bf(e),n=Hf(e);if(Wf(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[Vf(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let o=S();return{steps:t.stepTitles.map((r,i)=>({id:`${Xd}${String(i+1).padStart(3,"0")}`,order:i+1,title:r,body:t.templateSteps[i]?.body,status:"pending",created_at:o,updated_at:o})),hasPerStepDetailOptions:n}}function om(e,t,n=[]){le(e,t),n.length>0&&os(t,n)}async function Jf(e,t,n){let o=e.title?.trim();if(!o)throw new p("pm plan create requires --title",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let r=Qd(e.mode,Kr),i=Of(e.harness),s=e.fromSearch?.trim(),a=zf(e),{steps:c,hasPerStepDetailOptions:l}=Kf(e);if(c.length===0&&l)throw new p("pm plan create step options require --step-title (or a single --step)",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let d=e.description?.trim()??e.scope?.trim()??o,m=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:o,description:d,type:"Plan",template:void 0,file:V(e.file),test:V(e.test),doc:V(e.doc),field:V(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:qf(e),message:e.message??(s?`plan create (search: ${s})`:"plan create")};om(e,f);let g=await Ce(f,t),y=await qt({pmRoot:n.pmRoot,settings:n.settings,id:g.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(b){let v=["plan_mode"];b.metadata.plan_mode=r,i&&(b.metadata.plan_harness=i,v.push("plan_harness"));let _=e.scope?.trim();_&&(b.metadata.plan_scope=_,v.push("plan_scope"));let A=e.resumeContext?.trim();return A&&(b.metadata.plan_resume_context=A,v.push("plan_resume_context")),b.metadata.plan_steps=c,v.push("plan_steps"),a&&(b.metadata.plan_validation=[...b.metadata.plan_validation??[],a],v.push("plan_validation")),m&&(b.metadata.assignee=m,v.push("assignee")),{changedFields:v}}}),k=X(y.item,"brief");return{action:"create",plan:k,step:c[0],next_actions:Z(g.item.id,k),warnings:[...g.warnings],generated_at:S()}}async function Yf(e,t,n){let o=$f(t.depth),r=Ff(t.fields),{document:i,itemId:s}=await nm(n,e),a=X(i.metadata,r===null?o:"deep");return{action:"show",plan:r===null?a:Pf(a,r),next_actions:Z(s,a),warnings:[],generated_at:S()}}function Xf(e,t){let n=new Map(Object.entries(t).filter(([o])=>o.startsWith("plan_")).map(([o,r])=>[o,JSON.stringify(r)]));return[...new Set([...e.keys(),...n.keys()])].filter(o=>e.get(o)!==n.get(o))}async function ce(e){let t=C(e.options.author,e.ctx.settings.author_default),n,o=await qt({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(r){tm(r.metadata);let i=W(e.ctx.settings.schema);if(Ze(r.metadata.status,i)||er(r.metadata.plan_mode))throw new p(`Plan ${r.metadata.id} is terminal (status=${r.metadata.status}, plan_mode=${r.metadata.plan_mode??"unset"}) and cannot be mutated.`,u.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let s=(r.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(r.metadata).filter(([m])=>m.startsWith("plan_")).map(([m,f])=>[m,JSON.stringify(f)])),c=e.mutator(s,r);n=c.resultStep;let l=s.slice().sort((m,f)=>m.order-f.order).map((m,f)=>({...m,order:f+1}));r.metadata.plan_steps=l;let d=Xf(a,r.metadata);return d.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:d.length>0?d:["plan_steps"]}}});return{document:{metadata:o.item,body:o.body},resultStep:n,itemId:o.item.id}}async function Zf(e,t,n){let o=t.stepTitle?.trim();if(!o)throw new p("pm plan add-step requires --step-title",u.USAGE);let r=Jr(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:s,resultStep:a,itemId:c}=await ce({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${o}"`,mutator(d){let m=d.length+1;rm(d,void 0,r,i);let f=Qf(d,t,{order:m,title:o,status:r});return d.push(f),{changedSteps:[f.id],resultStep:f}}}),l=X(s.metadata,"standard");return{action:"add-step",plan:l,step:a,next_actions:Z(c,l),warnings:[],generated_at:S()}}function rm(e,t,n,o){if(n!=="in_progress"||o)return;let r=e.find(i=>i.id!==t&&i.status==="in_progress");if(r)throw new p(`Plan already has step ${r.id} in_progress. Pass --allow-multiple-active or update that step first.`,u.CONFLICT)}function Qf(e,t,n){let o=ei(t,"depends_on"),r=V(t.file).map(Xr),i=V(t.test).map(Zr),s=V(t.doc).map(Qr),a=S();return{id:Lf(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:ti(t.stepOwner),evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:r.length>0?r:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function ei(e,t){let n=te(e.dependsOn).map(d=>({id:d,kind:t})),o=te(e.related).map(d=>({id:d,kind:"related"})),r=te(e.blocks).map(d=>({id:d,kind:"blocks"})),i=te(e.blockedBy).map(d=>({id:d,kind:"blocked_by"})),s=te(e.link),a=em(e.linkKind,t),c=e.linkNote?.trim(),l=s.map(d=>{let m={id:d,kind:a};return c&&(m.note=c),m});return[...n,...o,...r,...i,...l]}async function Hr(e,t,n,o){let{document:r,resultStep:i,itemId:s}=await ce({id:e,options:t,ctx:n,op:o.op,message:t.message??`${o.op} ${o.stepRef}`,mutator(c,l){let d=dt(c,o.stepRef),m=S(),f=o.finalStatus??Jr(t.stepStatus,d.status),g=t.allowMultipleActive===!0||o.allowMultipleActive===!0;return rm(c,d.status==="in_progress"?d.id:void 0,f,g),e_(d,t,f,m),l.metadata.updated_at=m,{changedSteps:[d.id],resultStep:d}}}),a=X(r.metadata,"standard");return{action:o.op==="plan_complete_step"?"complete-step":o.op==="plan_block_step"?"block-step":"update-step",plan:a,step:i,next_actions:Z(s,a),warnings:[],generated_at:S()}}function ti(e){return cs(e?.trim(),"--step-owner")||void 0}function e_(e,t,n,o){t_(e,t,n),n_(e,t),e.status=n,e.updated_at=o,o_(e,n,o)}function t_(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new p("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",u.USAGE)}function n_(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=ti(t.stepOwner)),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let o=V(t.file).map(Xr),r=V(t.test).map(Zr),i=V(t.doc).map(Qr);o.length>0&&(e.files=Br(e.files,o)),r.length>0&&(e.tests=Br(e.tests,r)),i.length>0&&(e.docs=Br(e.docs,i))}function Br(e,t){let n=[...e??[]],o=new Set(n.map(r=>JSON.stringify(r)));for(let r of t){let i=JSON.stringify(r);o.has(i)||(o.add(i),n.push(r))}return n}function o_(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function r_(e,t,n,o,r){let{document:i,itemId:s,resultStep:a}=await ce({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${o} -> ${r}`,mutator(l){let d=dt(l,o),m=l.filter(g=>g.id!==d.id),f=Math.max(1,Math.min(r,m.length+1));return m.splice(f-1,0,d),m.forEach((g,y)=>{g.order=y+1,g.updated_at=S()}),l.length=0,l.push(...m),{changedSteps:[d.id],resultStep:d}}}),c=X(i.metadata,"standard");return{action:"reorder-step",plan:c,step:a,next_actions:Z(s,c),warnings:[],generated_at:S()}}async function i_(e,t,n,o){let{document:r,itemId:i,resultStep:s}=await ce({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${o}`,mutator(c){let l=dt(c,o),d=c.filter(m=>m.id!==l.id);return d.forEach((m,f)=>{m.order=f+1}),c.length=0,c.push(...d),{changedSteps:[l.id],resultStep:l}}}),a=X(r.metadata,"standard");return{action:"remove-step",plan:a,step:s,next_actions:Z(i,a),warnings:[],generated_at:S()}}async function s_(e,t,n,o){let r=ei(t,em(t.linkKind,"related"));if(r.length===0)throw new p("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",u.USAGE);let i=t.promoteToItemDep===!0,{document:s,itemId:a,resultStep:c}=await ce({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${o}`,mutator(d,m){let f=dt(d,o),g=f.linked_items??[],y=b=>`${b.kind}:${b.id}`,k=new Set(g.map(y));for(let b of r){let v=y(b);k.has(v)||(g.push(b),k.add(v))}if(f.linked_items=g,f.updated_at=S(),i){let b=m.metadata.dependencies??[],v=A=>`${A.kind}:${A.id}`,_=new Set(b.map(v));for(let A of r){let N=A.kind==="depends_on"?"blocked_by":A.kind,O={id:A.id,kind:N,created_at:S(),author:C(t.author,n.settings.author_default)};_.has(v(O))||(b.push(O),_.add(v(O)))}m.metadata.dependencies=b}return{changedSteps:[f.id],resultStep:f}}}),l=X(s.metadata,"standard");return{action:"link",plan:l,step:c,next_actions:Z(a,l),warnings:[],generated_at:S()}}async function a_(e,t,n,o){let r=te(t.link);if(r.length===0)throw new p("pm plan unlink requires --link <id> to remove",u.USAGE);let{document:i,itemId:s,resultStep:a}=await ce({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${o}`,mutator(l){let d=dt(l,o),m=(d.linked_items??[]).filter(f=>!r.includes(f.id));return d.linked_items=m.length>0?m:void 0,d.updated_at=S(),{changedSteps:[d.id],resultStep:d}}}),c=X(i.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Z(s,c),warnings:[],generated_at:S()}}async function Wr(e,t,n,o){let r=Df(o,t);if(!r){let l=`--${o}-text`,d=`--${o}`;throw new p(`pm plan ${o} requires ${l}`,u.USAGE,{code:"missing_required_option",examples:[`pm plan ${o} <plan-id> ${l} "..."`,`pm plan ${o} <plan-id> ${d} "..."`],recovery:{suggested_retry:`pm plan ${o} <plan-id> ${l} <value>`}})}let i=C(t.author,n.settings.author_default),{document:s,itemId:a}=await ce({id:e,options:t,ctx:n,op:`plan_append_${o}`,message:t.message??`plan ${o} append`,mutator(l,d){let m=S();if(o==="decision"){let g=d.metadata.plan_decisions??[];return g.push({ts:m,author:i,decision:r,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),d.metadata.plan_decisions=g,{changedSteps:[]}}if(o==="discovery"){let g=d.metadata.plan_discoveries??[];return g.push({ts:m,author:i,text:r}),d.metadata.plan_discoveries=g,{changedSteps:[]}}let f=d.metadata.plan_validation??[];return f.push({text:r,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),d.metadata.plan_validation=f,{changedSteps:[]}}}),c=X(s.metadata,"deep");return{action:o,plan:c,next_actions:Z(a,c),warnings:[],generated_at:S()}}async function c_(e,t,n){let o=t.resumeContext?.trim();if(!o)throw new p("pm plan resume requires --resume-context <text>",u.USAGE);let{document:r,itemId:i}=await ce({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=o;let l=t.scope?.trim();return l&&(c.metadata.plan_scope=l),{changedSteps:[]}}}),s=X(r.metadata,"brief");return{action:"resume",plan:s,next_actions:Z(i,s),warnings:[],generated_at:S()}}async function l_(e,t,n){let o=Qd(t.mode??"approved","approved"),{document:r,itemId:i}=await ce({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${o}`,mutator(a,c){c.metadata.plan_mode=o;let l=t.scope?.trim();return l&&(c.metadata.plan_scope=l),{changedSteps:[]}}}),s=X(r.metadata,"brief");return{action:"approve",plan:s,next_actions:Z(i,s),warnings:[],generated_at:S()}}function im(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function d_(e,t){let n=X(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Z(e.itemId,n),warnings:im(t),generated_at:S()}}function m_(e,t,n){let o=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let r of n.linked_items??[]){let i=r.kind==="blocked_by"||r.kind==="blocks"||r.kind==="related"||r.kind==="discovered_from"?r.kind:"related";o.push(`id=${r.id},kind=${i}`)}return o}async function p_(e){let t=[],n={},o=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let r of V(e.options.field)){let i=r.indexOf("=");if(i<=0)throw new p(`Invalid --field entry "${r}"; expected name=value`,u.USAGE);let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(s.length===0)throw new p(`Invalid --field entry "${r}"; expected name=value`,u.USAGE);let c=s.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new p(`Invalid --field entry "${r}"; expected name=value`,u.USAGE);let[l,...d]=c,m=`${l}${d.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(o.has(m))throw new p(`Invalid --field entry "${r}"; "${m}" is reserved by materialize and cannot be overridden`,u.USAGE);n[m]=a}for(let r of e.targets){let i={...n,title:r.title,description:r.body?.trim()||r.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${r.id}`,dep:m_(e.parent,e.planItemId,r)};om(e.options,i,["description",...Object.keys(n)]);let s=await Ce(i,{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:r.id})}return t}function u_(e,t,n){for(let o of t){let r=n.find(a=>a.from_step===o.id);if(!r)continue;let i=e.find(a=>a.id===o.id);if(!i)continue;let s=i.linked_items??[];s.push({id:r.id,kind:"implements",note:`materialized as ${r.type}`}),i.linked_items=s,i.updated_at=S()}}async function f_(e,t,n){let o=te(t.steps);if(o.length===0)throw new p("pm plan materialize requires --steps <ids|orders|all>",u.USAGE);let r=t.materializeType?.trim()||"Task",i=F(n.settings,T()),s=un(r,i);if(!s)throw new p(`Invalid --materialize-type "${r}"`,u.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,l=await nm(n,e),d=(l.document.metadata.plan_steps??[]).slice(),{targets:m,skipped:f}=Mf(d,o);if(m.length===0){if(f.length>0)return d_(l,f);throw new p("No matching plan steps found for --steps",u.NOT_FOUND)}let g=await p_({targets:m,parent:a,planItemId:l.itemId,resolvedTypeName:s,tags:c,options:t,pmRoot:n.pmRoot}),{document:y,itemId:k}=await ce({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${o.join(",")}`,mutator(v){return u_(v,m,g),{changedSteps:m.map(_=>_.id)}}}),b=X(y.metadata,"standard");return{action:"materialize",plan:b,materialized:g,...f.length>0?{materialize_skipped:f}:{},next_actions:Z(k,b),warnings:im(f),generated_at:S()}}function __(e){if(e.subcommand==="create")return e;let t=Zd(e.options.step);if(t.length>1)throw new p(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,u.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:le(e.options,{...e.options,stepTitle:t[0]})}:e}function ge(e,t){if(!e.id)throw new p(`pm plan ${t} requires a plan id`,u.USAGE);return e.id}function He(e,t){let n=ge(e,t);if(!e.stepRef)throw new p(`pm plan ${t} requires <plan-id> <step>`,u.USAGE);return{id:n,stepRef:e.stepRef}}function h_(e){let t=He(e,"reorder-step");if(e.reorderTo===void 0)throw new p("pm plan reorder-step requires <plan-id> <step> <new-order>",u.USAGE);return{...t,reorderTo:e.reorderTo}}var g_={create:(e,t)=>Jf(e.options,e.global,t),show:(e,t)=>Yf(ge(e,"show"),e.options,t),"add-step":(e,t)=>Zf(ge(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=He(e,"update-step");return Hr(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=He(e,"complete-step");return Hr(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=He(e,"block-step");return Hr(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=h_(e);return r_(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=He(e,"remove-step");return i_(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=He(e,"link");return s_(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=He(e,"unlink");return a_(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Wr(ge(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Wr(ge(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Wr(ge(e,"validation"),e.options,t,"validation"),resume:(e,t)=>c_(ge(e,"resume"),e.options,t),approve:(e,t)=>l_(ge(e,"approve"),e.options,t),materialize:(e,t)=>f_(ge(e,"materialize"),e.options,t)};function y_(e){let t=g_[e];if(!t)throw ae({command_path:"plan",token:e,allowed:Cf});return t}async function sm(e){let t=await Uf(e.global),n=__(e),o=await y_(n.subcommand)(n,t);return o.action==="show"?o:{...o,mutation_receipt:oo(o,t.pmRoot)}}var cm=2,oi="update-many",b_=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),w_=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),v_={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},k_=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],lm=e=>{let t={};for(let[n,o]of Object.entries(e))b_.has(n)||o!==void 0&&(t[n]=o);return t},S_=e=>Object.keys(lm(e)).length>0,dm=e=>typeof e=="string"?e.trim():e,A_=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},ni=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},x_=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??dm(e)},I_={priority:A_,estimatedMinutes:ni,order:ni,rank:ni,regression:x_},E_=(e,t)=>{if(t!==void 0)return(I_[e]??dm)(t)},ro=(e,t)=>ee(e,t),C_=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],R_=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,T_=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",am=(e,t)=>t===void 0?void 0:e[t],mt=e=>Array.isArray(e)?e.length:0,O_=(e,t,n)=>{let o=n[e.addKey],r=am(n,e.removeKey),i=mt(o),s=mt(r),a=n[e.clearKey]===!0,c=am(n,e.replaceKey)===!0;if(![a,c,i>0,s>0].includes(!0))return;let l=C_(e.field,t[e.field]);return{field:e.field,before:l,after:{operation:T_({replace:c,clear:a,removeCount:s}),clear:a,replace:c,add_count:i,remove_count:s,before_count:R_(e.field,l)}}},$_=(e,t)=>{let n=[];for(let o of k_){let r=O_(o,e,t);r!==void 0&&n.push(r)}return n},F_=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],P_=(e,t)=>{if(![t.tags!==void 0,mt(t.addTags)>0,mt(t.removeTags)>0].includes(!0))return;let n=F_(e.tags),o=t.tags===void 0?n:$t(t.tags),r=es(o,t.addTags),i=ts(r,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),s=n.slice().sort((a,c)=>a.localeCompare(c));if(!ro(s,i))return{field:"tags",before:n,after:i}},N_=(e,t)=>{let n=e.acceptance_criteria,o=Qi(Zi(n),t.addAc,t.removeAc);if(o.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,u.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals});let r=o.criteria.join("; ");if(!ro(typeof n=="string"?n:"",r))return{field:"acceptance_criteria",before:n,after:r}},L_=(e,t,n)=>{for(let[o,r]of Object.entries(v_)){let i=n[o];if(i===void 0)continue;let s=t[r],a=E_(o,i);ro(s,a)||e.push({field:r,before:s,after:a})}},M_=(e,t,n,o)=>{let r=bs(n,o,["update_many"]);for(let[i,s]of Object.entries(r)){let a=t[i];ro(a,s)||e.push({field:i,before:a,after:s})}},D_=(e,t,n,o)=>{if(n===void 0||n.length===0)return;let r=fr(n,o,pe(T()),["update_many"]);for(let i of r){let s=t[i];s!==void 0&&e.push({field:i,before:s,after:null})}},j_=(e,t,n={})=>{let o=e,r=[],i=P_(o,n);if(i&&r.push(i),L_(r,o,n),mt(n.addAc)>0||mt(n.removeAc)>0){let s=N_(o,n);s!==void 0&&r.push(s)}return r.push(...$_(o,n)),M_(r,o,n,t),D_(r,o,n.unset,t),{id:e.id,changes:r}},G_=(e,t)=>na(e,t,{strict:!0,flagLabel:"--filter-status"}),U_=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)},q_=[({update:e})=>{e.priority!==void 0&&xn(e.priority)},({update:e,settings:t})=>{e.unset!==void 0&&e.unset.length>0&&fr(e.unset,Xe(t.schema),pe(T()),["update_many"])},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let o=F(t,T());if(!un(e.type,o))throw new p(sa(e.type,o.types,gs(n,t.schema)),u.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!Ne(e.status,t)){let n=t.definitions.map(o=>o.id);throw new p(`Invalid status value "${e.status}". Allowed: ${n.join(", ")}`,u.USAGE,{code:"invalid_argument_value",field:"status",value:e.status,allowed:n})}},({update:e})=>{e.deadline!==void 0&&us(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&ss(e.estimatedMinutes,"estimated-minutes")}],z_=(e,t,n,o)=>{let r={update:e,settings:t,statusRegistry:n,pmRoot:o};for(let i of q_)i(r)},H_=async e=>{let t=await yn(e.pmRoot,oi,e.rollbackId,cm),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,o=await to(e.pmRoot,t,{author:e.options.update?.author,message:n,force:e.options.update?.force}),r=o.rows.filter(i=>i.status==="skipped").length;return{...je({applied:o.restored_ids.length,skipped:r,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:o.restored_ids.length,skipped_count:r,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}},B_=async e=>{let t={schema_version:cm,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await gn(e.pmRoot,oi,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},W_=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(r=>r.trim()).filter(r=>r.length>0))],o=new Set(t.map(r=>r.id));return n.filter(r=>!o.has(r))},ri=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},V_=async e=>{let t=x(process.cwd(),e.path);await P(t);let n=await I(t);return{pmRoot:t,settings:n,statusRegistry:W(n.schema),runtimeFieldRegistry:Xe(n.schema)}},K_=e=>{if(e.options.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(Jt(e.options.list,e.options.status))throw new p("Rollback mode does not accept filter options",u.USAGE);if(Object.keys(e.updateSummary).length>0)throw new p("Rollback mode does not accept update mutation flags",u.USAGE);return H_({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},J_=async e=>{G_(e.options.status,e.runtime.statusRegistry);let t=await _e(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(r=>{let i=j_(r,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),o=e.options.list?.ids==null?[]:(await _e(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(r=>r.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:W_(e.options.list?.ids,o)}},Y_=e=>({outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...ri(e)}),X_=e=>({...je({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...ri(e)}),Z_=async e=>{let t=[],n=[],o=e.options.update.message??`update-many apply ${e.checkpointId}`,r=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!r.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let s=Ao(le(e.options.update,{...e.options.update,message:o,runtimeFieldCommands:["update_many"]})),a=await Rn({pmRoot:e.pmRoot,itemId:i.id,checkpointId:e.checkpointId},()=>lt(i.id,s,e.global));t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(s){let a=await Kn(s,i.id,e.pmRoot);if(a!==void 0){t.push({id:i.id,status:"updated",...a}),n.push(i.id);continue}t.push({id:i.id,status:"failed",error:Ae(s),...await ot(s,e.pmRoot)})}}return{rows:t,updatedIds:n}},Q_=async e=>{if(e.plan.actionable.length===0)return X_(e.plan);let t=S(),n=hn(oi,t),o=new Set(e.plan.actionable.map(m=>m.id)),r=e.plan.listed.items.filter(m=>o.has(m.id)).map(m=>({id:m.id,target_updated_at:m.updated_at})),i=e.options.checkpoint===!1?void 0:await B_({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:r}),s=await Z_({pmRoot:e.runtime.pmRoot,items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=m=>s.rows.filter(f=>f.status===m).length,c=a("updated"),l=a("skipped"),d=a("failed");return{...je({applied:c,skipped:l,failed:d,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:l,failed_count:d,rows:s.rows,ids:s.updatedIds,...ri(e.plan)}},mm=async(e,t)=>{let n=_n(e.rollback),o=await V_(t);n===void 0&&(e={...e,update:Ao(await Ql(e.update))});let r=lm(e.update);if(U_(e.list),n!==void 0)return K_({runtime:o,rollbackId:n,options:e,global:t,updateSummary:r});if(!S_(e.update)&&e.dryRun!==!0)throw new p(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${w_}), or pass --dry-run for a filter-only preview.`,u.USAGE);z_(e.update,o.settings,o.statusRegistry,o.pmRoot),ed(e.update);let i=await pr({pmRoot:o.pmRoot,dependencies:_r(e.update.dep,o.settings.id_prefix,S(),C(e.update.author,o.settings.author_default)).additions,idPrefix:o.settings.id_prefix,itemFormat:o.settings.item_format,typeToFolder:F(o.settings,T()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),s=await J_({options:e,global:t,runtime:o,updateSummary:r,dependencyWarnings:i});return await pr({pmRoot:o.pmRoot,dependencies:_r(e.update.dep,o.settings.id_prefix,S(),C(e.update.author,o.settings.author_default)).additions,idPrefix:o.settings.id_prefix,itemFormat:o.settings.item_format,typeToFolder:F(o.settings,T()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:s.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:o.settings.schema}),e.dryRun===!0?Y_(s):Q_({runtime:o,options:e,global:t,plan:s})};function eh(e){if(e===void 0)return;if(e.trim().length===0)throw new p("--add-json must contain a JSON value",u.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new p("--add-json must be valid JSON",u.USAGE,{code:"structured_event_json_invalid"})}return t}function th(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function nh(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new p("--since must be a valid ISO timestamp",u.USAGE,{code:"structured_event_since_invalid"});return t}function pm(e){return Object.prototype.toString.call(e)==="[object Object]"?e:{}}async function um(e,t,n){let o=eh(t.addJson),r=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(o!==void 0&&r)throw new p("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",u.USAGE,{code:"structured_event_input_conflict"});let i=o===void 0?void 0:Ot(o),s=[t.since,t.eventType].some(y=>y!==void 0),a=nh(t.since),c=oa(t.limit),l=await it(e,{...t,...s?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,s].includes(!0)},n,{input:await Ln(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:y=>rt(y),createEntry:y=>o===void 0?y:{...y,format:"json",data:o,event_type:th(o)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm notes --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}}),d=t.eventType?.trim(),m=l.notes.filter(y=>{let k=pm(y),b=[k.format==="json",k.data!==void 0].every(Boolean),v=[a===void 0,Date.parse(k.created_at??"")>=(a??Number.POSITIVE_INFINITY)].includes(!0),_=[!d,k.event_type===d].includes(!0);return[!s,[b,v,_].every(Boolean)].includes(!0)}),f=s?Ec(m,c):m,g=f.filter(y=>pm(y).format==="json").length;return{...l,notes:f,count:f.length,...s?{total_count:m.length,returned_count:f.length,has_more:f.length<m.length,...c===void 0?{}:{limit:c},structured_event_count:g}:t.includeMeta===!0?{structured_event_count:g}:{}}}import Ah from"node:path";var pt=["agile","ops","research"],ii={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:Un.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
11
+ `,{changedFields:["body"]}}});return{item:l.item,appended:c,changed_fields:l.changedFields}}function nf(e,t,n){let o={...t.metadata,body:t.body},r={...n.metadata,body:n.body};for(let i of new Set([...Object.keys(o),...Object.keys(r)])){if(i==="updated_at"||i==="pm_format_version")continue;let s=o[i],a=r[i];if(J(s,a))continue;let c=e.get(i);if(c&&!J(c.after,s))throw new p(`Rollback conflict on ${i}: the batch effects contain an intervening edit. Inspect pm history before resolving it.`,u.CONFLICT);e.set(i,{field:i,before:c?c.before:s,after:a})}}function of(e,t,n){let o=new Map;for(let[r,i]of e.entries()){if(i.context?.bulk_checkpoint!==t)continue;let s=Po(Vo(e,r-1),{schema:n}),a=Po(Vo(e,r),{schema:n});nf(o,s,a)}return[...o.values()].filter(r=>!J(r.before,r.after))}function rf(e,t){let n={...e.metadata,body:e.body},o=t.filter(r=>!J(n[r.field],r.after));if(o.length>0)throw new p(`Rollback conflict on ${o.map(r=>r.field).join(", ")}: a later edit changed a batch field. Inspect pm get/history and reconcile it explicitly before retrying.`,u.CONFLICT);for(let r of t)r.field==="body"?e.body=r.before:r.before===void 0?delete e.metadata[r.field]:e.metadata[r.field]=structuredClone(r.before);return t.map(r=>r.field)}async function to(e,t,n){if(t.record.rollback_strategy!=="guarded_inverse")throw new p("This legacy checkpoint has no attributable inverse effects. Inspect pm history and use an explicit pm restore only after reviewing later edits.",u.CONFLICT);let o=await I(e),r=new Map,i=await fs(t.items,async a=>{try{return await sf(e,o,t,a,n)}catch(c){throw r.set(a,c),c}}),s=[];for(let a of i.rows)s.push(a.status==="failed"?{...a,...await ot(r.get(a.id),e)}:a);return{...i,rows:s}}async function sf(e,t,n,o,r){let i=await ba({pmRoot:e,settings:t,id:o,op:"restore",author:C(r.author,t.author_default),message:r.message,force:r.force,skipNoop:!0,historyContext:{bulk_rollback:n.id},async mutate(s){let a=await Cs(me(e,o),o);if(!Ma(a,s).ok)throw new p(`Cannot safely roll back ${o}: item/history verification failed. Inspect pm history --verify before recovery.`,u.CONFLICT);return a.some(l=>l.context?.bulk_rollback===n.id)?{changedFields:[]}:{changedFields:rf(s,of(a,n.id,t.schema))}}});return{changed_fields:i.changedFields,warnings:i.warnings,skipped:i.changedFields.length===0}}var qd=2,Mr="close-many",af=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function cf(e,t){return Jt(e,t,{includePagination:!1})}function lf(e,t){return Jt(e,t)}function df(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)}function mf(e){let t={};if(!e)return t;for(let[n,o]of Object.entries(e))o==null||typeof o=="string"&&!o.split(",").some(r=>r.trim().length>0)||(t[n]=o);return t}function pf(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new p("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",u.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function uf(e,t){let n=W(t.schema),o=F(t,T()),r=await Ut(e,t.item_format,o.type_to_folder,void 0,t.schema),i=new Map,s=new Map;for(let a of r){if(typeof a.parent!="string"||a.parent.length===0||(s.set(a.id,a.parent),Ze(a.status,n)))continue;let c=i.get(a.parent);c?c.push(a.id):i.set(a.parent,[a.id])}for(let a of i.values())a.sort((c,l)=>c.localeCompare(l));return{childrenByParent:i,parentByChild:s}}function Ud(e,t,n){let o=n?.get(e);if(o!==void 0)return o;let r=0,i=t.get(e),s=[],a=new Set,c=!1;for(;i!==void 0&&!a.has(i);){let l=n?.get(i);if(l!==void 0){r+=l+1;break}a.add(i),s.push(i),r+=1,i=t.get(i)}if(i!==void 0&&a.has(i)&&(c=!0),!c){n?.set(e,r);for(let[l,d]of s.entries())n?.set(d,r-l-1)}return r}async function ff(e){let t=await yn(e.pmRoot,Mr,e.rollbackId,qd),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,o=await to(e.pmRoot,t,{author:e.options.author,message:n,force:e.options.force}),r=o.rows.filter(i=>i.status==="skipped").length;return{...je({applied:o.restored_ids.length,skipped:r,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:o.restored_ids.length,skipped_count:r,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}}function _f(e,t,n,o,r){return e.map(i=>{let s=(t.get(i.id)??[]).filter(c=>!n.has(c)),a=!zd(i,o,r);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...s.length>0?{active_child_ids:s}:{}}})}async function hf(e){let t=await gn(e.pmRoot,Mr,e.checkpointId,{schema_version:qd,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function gf(e){let t=[],n=[];for(let o of e.matched){if(!e.closableIds.has(o.id)){t.push({id:o.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let r=await Tn({pmRoot:e.pmRoot,itemId:o.id,checkpointId:e.checkpointId},()=>Kt(o.id,e.reason,e.closeOptions,e.global));t.push({id:o.id,status:"closed",completion:r.completion,changed_fields:r.changed_fields,...r.warnings&&r.warnings.length>0?{warnings:r.warnings}:{}}),n.push(o.id)}catch(r){let i=await Kn(r,o.id,e.pmRoot);if(i!==void 0){t.push({id:o.id,status:"closed",...i}),n.push(o.id);continue}t.push({id:o.id,status:"failed",error:Ae(r),...await ot(r,e.pmRoot)})}}return{rows:t,closedIds:n}}function yf(e){return _n(e.rollback)}function bf(e){if(e.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(lf(e.list,e.status))throw new p("Rollback mode does not accept filter options",u.USAGE)}function wf(e){if(!cf(e.list,e.status))throw new p(`close-many requires at least one filter to scope the close (for example: ${af}). Refusing to match every item.`,u.USAGE)}function vf(e,t){let n=new Map;return[...e].sort((o,r)=>{let i=Ud(r.id,t,n)-Ud(o.id,t,n);return i!==0?i:o.id.localeCompare(r.id)})}function zd(e,t,n){return n||!Ze(e.status,t)}function kf(e,t,n){return new Set(e.filter(o=>zd(o,t,n)).map(o=>o.id))}async function Sf(e){wf(e.options);let t=W(e.settings.schema),n=pf(e.options.reason,e.settings.governance.require_close_reason),o=e.options.force===!0,r=await _e(e.options.status,mf(e.options.list),e.global),{childrenByParent:i,parentByChild:s}=await uf(e.pmRoot,e.settings),a=vf(r.items,s),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],l=c.length===0?[]:(await _e(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,d=new Set(l.map(f=>f.id)),m=kf(a,t,o);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:o,listed:r,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!d.has(f)),planRows:_f(a,i,m,t,o)}}function Af(e){return{outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function xf(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return hf({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function Hd(e,t){let n=yf(e),o=x(process.cwd(),t.path);await P(o);let r=await I(o),i=e.dryRun===!0;if(df(e.list),n!==void 0)return bf(e),ff({pmRoot:o,rollbackId:n,options:e,global:t});let s=await Sf({pmRoot:o,settings:r,options:e,global:t});if(i)return Af(s);let a=new Set(s.planRows.filter(v=>v.action==="close").map(v=>v.id)),c=S(),l=hn(Mr,c),d=await xf({context:s,options:e,closableIds:a,checkpointId:l,nowValue:c}),m={author:e.author,message:e.message??`close-many apply ${l}`,completedAt:e.completedAt,validateClose:s.validateCloseMode,force:s.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:g}=await gf({pmRoot:o,checkpointId:l,matched:s.matched,closableIds:a,reason:s.reason,closeOptions:m,global:t}),y=f.filter(v=>v.status==="closed").length,k=f.filter(v=>v.status==="skipped").length,b=f.filter(v=>v.status==="failed").length;return{...je({applied:y,skipped:k,failed:b,unmatched:s.unmatchedIds?.length??0}),mode:"apply",matched_count:s.matched.length,dry_run:!1,...s.reason!==void 0?{reason:s.reason}:{},filters:s.listed.filters,...s.validateCloseMode?{validate_close:s.validateCloseMode}:{},...d?{checkpoint:d}:{},closed_count:y,skipped_count:k,failed_count:b,rows:f,ids:g,...s.unmatchedIds!==void 0?{unmatched_ids:s.unmatchedIds,unmatched_count:s.unmatchedIds.length}:{}}}function If(e,t){return[...new Set([...Wi.filter(o=>e[o]!==void 0),...Object.keys(e).filter(o=>e[o]!==void 0),...t.length>0?["body"]:[]])].sort((o,r)=>o.localeCompare(r))}function Ef(e,t){let n=`copied_from=${e}`;if(!t)return n;let o=t.trim();return o.length>0?`${o} | ${n}`:n}async function Dr(e,t,n){let o=x(process.cwd(),n.path);await P(o);let r=await I(o),i=F(r,T()),s=await oe(o,e,r.id_prefix,r.item_format,i.type_to_folder);if(!s)throw await $n(o,e,r.id_prefix,i.type_to_folder);let a=await xe(s,{schema:r.schema}),c=a.document.metadata,l=S(),d=C(t.author,r.author_default),m=await Ho(o,r.id_prefix,{tokenLength:r.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=W(r.schema),g=t.title?.trim();if(g!==void 0&&g.length===0)throw new p("Copy --title must not be empty",u.USAGE);let y={...c,id:m,title:g??c.title,status:f.open_status,created_at:l,updated_at:l};delete y.closed_at,delete y.completed_at,delete y.close_reason,delete y.test_runs;let k=ue(T()),b=Mt({metadata:y,body:a.document.body},{schema:r.schema,extensionFieldNames:k}),v=await cr({title:b.metadata.title,description:b.metadata.description,body:b.body,excludeIds:[s.id]},{pmRoot:o,mode:r.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":r.governance.duplicate_detection_mode,threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),_=If(b.metadata,b.body),A=Oo(o,b.metadata.type,m,r.item_format,i.type_to_folder),N=me(o,m),O=await Dt(o,m,r.locks.ttl_seconds,d,!1,r.governance.force_required_for_stale_lock,r.locks.wait_ms),B={metadata:{},body:""},$,R,ie;try{let Tt=await _a(o,d,{required:r.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{r.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await cr({title:b.metadata.title,description:b.metadata.description,body:b.body,excludeIds:[s.id]},{pmRoot:o,mode:"strict",threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:!1});let ne=await oe(o,m,r.id_prefix,r.item_format,i.type_to_folder);if(ne)throw new p(`Cannot copy to ${m}: an item with that id already exists at ${ne.itemPath}. Retry the copy to allocate a new id.`,u.CONFLICT,{code:"item_id_collision",why:`Allocated id ${m} already exists at ${ne.itemPath}.`,recovery:{suggested_retry:`pm copy ${s.id}`}});let Ve=await Rn({pmRoot:o,settings:r,operation:"create",author:d,before:null,after:b});ie=Ve.warnings,await xn({pm_root:o,operation:"create",before:null,after:b,changed_fields:_,author:d,sdk:On({pmRoot:o,settings:r,typeToFolder:i.type_to_folder})}),await O.fence(async()=>{await se(A,Lt(b,{format:r.item_format,schema:r.schema,extensionFieldNames:k}));try{let Ke=jt({nowIso:l,author:d,op:"create",before:B,after:b,message:Ef(s.id,t.message),context:Ve.decisions.length===0?void 0:{workflow_policies:Ve.decisions}});await Gt(N,Ke)}catch(Ke){throw await Ft(A),Ke}}),R=await ha({pmRoot:o,preferredFormat:r.item_format,typeToFolder:i.type_to_folder,schema:r.schema,itemPath:A,document:b})}finally{await Tt()}$=[...await G({path:A,scope:"project",op:"create",item_id:b.metadata.id,item_type:b.metadata.type,before:B,after:b,changed_fields:_}),...await G({path:N,scope:"project",op:"create:history",item_id:b.metadata.id,item_type:b.metadata.type,before:B,after:b,changed_fields:_})],Ks({id:b.metadata.id,op:"create",item_type:b.metadata.type,status:b.metadata.status,current:Js(b.metadata,_),changed_fields:_})}finally{await O.release()}return{source_id:s.id,item:structuredClone(b.metadata),changed_fields:_,warnings:[...xl(v),...ie,...R,...$],...v===void 0?{}:{similarity_advisory:v}}}import no from"node:path";async function jr(e,t,n){let o=x(process.cwd(),n.path);await P(o);let r=await I(o),i=C(t.author,r.author_default),s=await wa({pmRoot:o,settings:r,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),a=s.targetPath?no.relative(o,s.targetPath).split(no.sep).join("/"):void 0;return{item:s.item,changed_fields:s.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:s.item.status,...a?{target_path:a}:{},history_retained:no.relative(o,me(o,s.item.id)).split(no.sep).join("/"),tombstone_retention:"retain_append_only",warnings:s.warnings}}async function Cf(e){await P(e)}async function Gr(e,t,n){let o=x(process.cwd(),n.path);if(await Cf(o),t.clear===!0){if(e!==void 0)throw new p("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",u.USAGE);let m=await I(o),f=Fo(C(void 0,m.author_default));return await Es(o),await ur({pmRoot:o,settings:m,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let m=await xs(o);if(m===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await Rf(o,m);return{action:"show",focused_item:m,title:f,message:`Focused on ${m}${f?` (${f})`:""}. New items default --parent to it.`}}let i=await I(o),s=F(i,T()),a=await oe(o,e,i.id_prefix,i.item_format,s.type_to_folder);if(!a)throw await $n(o,e,i.id_prefix,s.type_to_folder);let c=zo(a.id,i.id_prefix),l=await xe(a,{schema:i.schema}),d=Bd(l.document.metadata.title);return await Is(o,c),await ur({pmRoot:o,settings:i,principal:Fo(C(void 0,i.author_default)),itemId:c}),{action:"set",focused_item:c,title:d,message:`Focused on ${c}${d?` (${d})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function Rf(e,t){let n=await I(e),o=F(n,T()),r=await oe(e,t,n.id_prefix,n.item_format,o.type_to_folder);if(!r)return null;let i=await xe(r,{schema:n.schema});return Bd(i.document.metadata.title)}function Bd(e){return e.trim().length>0?e:null}async function Ur(e,t,n,o){Ht(e,"reopen","id"),Ht(t,"reopen","reason"),Fc(n);let r=t.trim();if(r.length===0)throw new p("pm item reopen requires a non-empty recurrence reason.",u.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=x(process.cwd(),o.path),s=n.expectedResult?.trim();if(s!==void 0&&s.length===0)throw new p("Reopen expected result must describe the current active outcome.",u.USAGE);let a=W((await I(i)).schema),c=a.open_status,l=Zl(a),d=n.status??c,m=Ne(d,a)??d;if(m!==c&&m!==l)throw new p(`Reopen target status must be ${c} or ${l}; received ${d}.`,u.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([c,l])],suggested_retry:`pm item reopen ${e} "${r}" --status ${c}`,suggested_retry_args:["item","reopen",e,r,"--status",c]}});let f=await td(e,{status:m,expectedResult:s,unset:["close-reason","resolution",...s===void 0?["expected-result"]:[],"actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},o,r);return{item:f.item,changed_fields:f.changed_fields,warnings:f.warnings,recurrence:f.lifecycle_transition,...s===void 0?{recovery:{missing:["expected_result"],suggested_retry_args:["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"],suggested_retry:fn(["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"])}}:{}}}async function Wd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r=e.force===!0||o.force===!0,i={...e.args,...o},s=o.next===!0,a=e.id??h(o,"id");if(i.start===!0){if(a)return ze(e,"start_task");id(a,s,!0)}let c=s?await sd(r,e.global,i,i):await rd(Qt(e,o),r,e.global,i);return H(c,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Qt(e,t){let n=e.id??h(t,"id");if(!n)throw new p("Missing required argument: id",64);return n}function qr(e,t){return h(e.args,"reason")??h(e.args,"text")??h(t,"reason")??h(t,"text")}async function Vd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return o.releaseAssignment===!0?ze(e,"close_task"):H(await Kt(Qt(e,o),qr(e,o),{...o,force:e.force===!0||o.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function ze(e,t){let{changedFields:n,idOnly:o,runnerOptions:r}=j(e.args,e.options),i=Qt(e,r),s=st(r,{force:e.force===!0||r.force===!0}),a=t==="start_task"?await yr(i,s,e.global):t==="pause_task"?await br(i,s,e.global):await wr(i,qr(e,r),s,e.global);return H(a,{changedFields:n,idOnly:o,compactEnvelope:n==="compact"&&!o})}async function Kd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r=st(o,{message:h(Object.hasOwn(o,"message")?o:e.args,"message")});if(r.pause===!0)return ze({...e,options:r},"pause_task");let i=await ad(Qt(e,r),e.force===!0||r.force===!0,e.global,r);return H(i,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function Jd(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await Ur(Qt(e,o),qr(e,o)??"",{...o,force:e.force===!0||o.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function oo(e,t){let n=fn(["plan","show",e.plan.id,"--depth","deep",...t===void 0?[]:["--pm-path",t]]);return{kind:"plan_mutation",action:e.action,id:e.plan.id,status:e.plan.status,mode:e.plan.mode,steps_summary:e.plan.steps_summary,...e.step===void 0?{}:{step:{id:e.step.id,order:e.step.order,status:e.step.status}},materialized_count:e.materialized?.length??0,skipped_count:e.materialize_skipped?.length??0,warning_count:e.warnings.length,warnings:e.warnings.slice(0,3).map(o=>o.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(o=>o.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${as(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}var Tf=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"];var Zd="plan-step-",Kr="draft",Vr=["bug-investigation","feature-implementation","refactoring-sprint"],Yd={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function Of(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Yd,t)?Yd[t]:void 0;if(!n)throw new p(`Unknown plan template "${e}". Allowed: ${Vr.join(", ")}`,u.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Vr[0]}`]});return n.map(o=>({...o}))}function $f(e,t){return t>0?Math.round(e/t*100):0}function Qd(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function te(e){return Array.isArray(e)?e.flatMap(t=>Qo(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Qo(e,{unique:!1}):[]}function V(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function em(e,t=Kr){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Eo.find(r=>r===n);if(!o)throw new p(`Invalid plan mode "${e}". Allowed: ${Eo.join(", ")}`,u.USAGE);return o}function Jr(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Co.find(r=>r===n);if(!o)throw new p(`Invalid step status "${e}". Allowed: ${Co.join(", ")}`,u.USAGE);return o}function tm(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=To.find(r=>r===n);if(!o)throw new p(`Invalid step link kind "${e}". Allowed: ${To.join(", ")}`,u.USAGE);return o}function Ff(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ro.find(o=>o===t);if(!n)throw new p(`Invalid plan harness "${e}". Allowed: ${Ro.join(", ")}`,u.USAGE);return n}function Pf(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=tr.find(o=>o===t);if(!n)throw new p(`Invalid --depth "${e}". Allowed: ${tr.join(", ")}`,u.USAGE);return n}function Nf(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new p("Plan --fields requires a comma-separated list of plan field names",u.USAGE);return t}var zr=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function Lf(e,t){let n=e,o={},r=[];for(let i of t){let s=i.startsWith("plan.")?i.slice(5):i;if(s.length!==0){if(!zr.has(s)){r.push(i);continue}Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])}}if(r.length>0)throw new p(`Unknown Plan --fields value(s): ${r.join(", ")}`,u.USAGE,{nextSteps:[`Use --fields ${[...zr].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:r,suggested_retry:`pm plan show <id> --fields ${[...zr].join(",")}`}});return o}function Yr(e,t){let n={};for(let o of e.split(",")){let r=o.trim();if(r.length===0)continue;let i=r.indexOf("=");if(i<=0)throw new p(`Invalid ${t} entry "${r}"; expected key=value`,u.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[r.slice(0,i).trim().toLowerCase()]=r.slice(i+1).trim()}return n}function Xr(e){let t=Yr(e,"--file");if(!t.path)throw new p("--file requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Zr(e){let t=Yr(e,"--test");if(!t.command&&!t.path)throw new p("--test requires at least command=<value> or path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function Qr(e){let t=Yr(e,"--doc");if(!t.path)throw new p("--doc requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Mf(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=$f(t.completed,t.total),t}function Df(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let o=`${Zd}${String(n).padStart(3,"0")}`;if(!t.has(o))return o}throw new p("Could not allocate step id (limit reached)",u.GENERIC_FAILURE)}function dt(e,t){let n=t.trim();if(n.length===0)throw new p("Step reference cannot be empty",u.USAGE);let o=e.find(r=>r.id===n);if(o)return o;if(/^\d+$/.test(n)){let r=Number.parseInt(n,10),i=e.find(s=>s.order===r);if(i)return i}throw new p(`Step "${t}" not found in plan`,u.NOT_FOUND)}function Xd(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function jf(e,t){let n=t.filter(s=>s.trim().toLowerCase()==="all"),o=[],r=[];if(n.length>0){if(t.length>n.length)throw new p("pm plan materialize --steps all cannot be combined with other step refs",u.USAGE);for(let s of e.slice().sort((a,c)=>a.order-c.order)){let a=Xd(s);if(a){r.push({from_step:s.id,...a});continue}o.push(s)}return{targets:o,skipped:r}}let i=new Set;for(let s of t){let a=dt(e,s);if(i.has(a.id))continue;i.add(a.id);let c=Xd(a);if(c){r.push({from_step:a.id,...c});continue}o.push(a)}return{targets:o,skipped:r}}function Gf(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,o=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||o?.trim()||void 0}function Uf(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function qf(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Z(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((s,a)=>s.order-a.order),o=Mf(n),r=Uf(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Kr,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:o,current_step:r?{id:r.id,order:r.order,title:r.title,status:r.status}:void 0,blocked_steps:qf(n),linked_items:(e.dependencies??[]).map(s=>({id:s.id,kind:s.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function Q(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!er(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function nm(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new p(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,u.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function zf(e){let t=x(process.cwd(),e.path);await P(t);let n=await I(t);return{pmRoot:t,settings:n}}async function om(e,t){let n=F(e.settings,T()),o=await oe(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!o)throw new p(`Plan ${t} not found`,u.NOT_FOUND);let r=await xe(o,{schema:e.settings.schema});return nm(r.document.metadata),{document:r.document,itemId:o.id}}function Hf(e){let t=[];for(let n of te(e.related))t.push(`id=${n},kind=related`);for(let n of te(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of te(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function Bf(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),o=e.validationExpected?.trim();if(!(!t&&!n&&!o))return{text:t||n||"Validation check",command:n||void 0,expected:o||void 0}}function Wf(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||te(e.dependsOn).length>0||te(e.link).length>0}function Vf(e){let t=e.stepTitle?.trim()||void 0,n=Qd(e.step),o=e.template?.trim()?Of(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...o.map(r=>r.title)],templateSteps:o}}function Kf(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new p("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",u.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Vr[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new p("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",u.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function Jf(e,t){let n=Jr(e.stepStatus,"pending"),o=ei(e,"depends_on"),r=V(e.file).map(Xr),i=V(e.test).map(Zr),s=V(e.doc).map(Qr),a=S();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:ti(e.stepOwner),evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:r.length>0?r:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function Yf(e){let t=Vf(e),n=Wf(e);if(Kf(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[Jf(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let o=S();return{steps:t.stepTitles.map((r,i)=>({id:`${Zd}${String(i+1).padStart(3,"0")}`,order:i+1,title:r,body:t.templateSteps[i]?.body,status:"pending",created_at:o,updated_at:o})),hasPerStepDetailOptions:n}}function rm(e,t,n=[]){le(e,t),n.length>0&&os(t,n)}async function Xf(e,t,n){let o=e.title?.trim();if(!o)throw new p("pm plan create requires --title",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let r=em(e.mode,Kr),i=Ff(e.harness),s=e.fromSearch?.trim(),a=Bf(e),{steps:c,hasPerStepDetailOptions:l}=Yf(e);if(c.length===0&&l)throw new p("pm plan create step options require --step-title (or a single --step)",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let d=e.description?.trim()??e.scope?.trim()??o,m=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:o,description:d,type:"Plan",template:void 0,file:V(e.file),test:V(e.test),doc:V(e.doc),field:V(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:Hf(e),message:e.message??(s?`plan create (search: ${s})`:"plan create")};rm(e,f);let g=await Ce(f,t),y=await qt({pmRoot:n.pmRoot,settings:n.settings,id:g.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(b){let v=["plan_mode"];b.metadata.plan_mode=r,i&&(b.metadata.plan_harness=i,v.push("plan_harness"));let _=e.scope?.trim();_&&(b.metadata.plan_scope=_,v.push("plan_scope"));let A=e.resumeContext?.trim();return A&&(b.metadata.plan_resume_context=A,v.push("plan_resume_context")),b.metadata.plan_steps=c,v.push("plan_steps"),a&&(b.metadata.plan_validation=[...b.metadata.plan_validation??[],a],v.push("plan_validation")),m&&(b.metadata.assignee=m,v.push("assignee")),{changedFields:v}}}),k=Z(y.item,"brief");return{action:"create",plan:k,step:c[0],next_actions:Q(g.item.id,k),warnings:[...g.warnings],generated_at:S()}}async function Zf(e,t,n){let o=Pf(t.depth),r=Nf(t.fields),{document:i,itemId:s}=await om(n,e),a=Z(i.metadata,r===null?o:"deep");return{action:"show",plan:r===null?a:Lf(a,r),next_actions:Q(s,a),warnings:[],generated_at:S()}}function Qf(e,t){let n=new Map(Object.entries(t).filter(([o])=>o.startsWith("plan_")).map(([o,r])=>[o,JSON.stringify(r)]));return[...new Set([...e.keys(),...n.keys()])].filter(o=>e.get(o)!==n.get(o))}async function ce(e){let t=C(e.options.author,e.ctx.settings.author_default),n,o=await qt({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(r){nm(r.metadata);let i=W(e.ctx.settings.schema);if(Ze(r.metadata.status,i)||er(r.metadata.plan_mode))throw new p(`Plan ${r.metadata.id} is terminal (status=${r.metadata.status}, plan_mode=${r.metadata.plan_mode??"unset"}) and cannot be mutated.`,u.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let s=(r.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(r.metadata).filter(([m])=>m.startsWith("plan_")).map(([m,f])=>[m,JSON.stringify(f)])),c=e.mutator(s,r);n=c.resultStep;let l=s.slice().sort((m,f)=>m.order-f.order).map((m,f)=>({...m,order:f+1}));r.metadata.plan_steps=l;let d=Qf(a,r.metadata);return d.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:d.length>0?d:["plan_steps"]}}});return{document:{metadata:o.item,body:o.body},resultStep:n,itemId:o.item.id}}async function e_(e,t,n){let o=t.stepTitle?.trim();if(!o)throw new p("pm plan add-step requires --step-title",u.USAGE);let r=Jr(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:s,resultStep:a,itemId:c}=await ce({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${o}"`,mutator(d){let m=d.length+1;im(d,void 0,r,i);let f=t_(d,t,{order:m,title:o,status:r});return d.push(f),{changedSteps:[f.id],resultStep:f}}}),l=Z(s.metadata,"standard");return{action:"add-step",plan:l,step:a,next_actions:Q(c,l),warnings:[],generated_at:S()}}function im(e,t,n,o){if(n!=="in_progress"||o)return;let r=e.find(i=>i.id!==t&&i.status==="in_progress");if(r)throw new p(`Plan already has step ${r.id} in_progress. Pass --allow-multiple-active or update that step first.`,u.CONFLICT)}function t_(e,t,n){let o=ei(t,"depends_on"),r=V(t.file).map(Xr),i=V(t.test).map(Zr),s=V(t.doc).map(Qr),a=S();return{id:Df(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:ti(t.stepOwner),evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:r.length>0?r:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function ei(e,t){let n=te(e.dependsOn).map(d=>({id:d,kind:t})),o=te(e.related).map(d=>({id:d,kind:"related"})),r=te(e.blocks).map(d=>({id:d,kind:"blocks"})),i=te(e.blockedBy).map(d=>({id:d,kind:"blocked_by"})),s=te(e.link),a=tm(e.linkKind,t),c=e.linkNote?.trim(),l=s.map(d=>{let m={id:d,kind:a};return c&&(m.note=c),m});return[...n,...o,...r,...i,...l]}async function Hr(e,t,n,o){let{document:r,resultStep:i,itemId:s}=await ce({id:e,options:t,ctx:n,op:o.op,message:t.message??`${o.op} ${o.stepRef}`,mutator(c,l){let d=dt(c,o.stepRef),m=S(),f=o.finalStatus??Jr(t.stepStatus,d.status),g=t.allowMultipleActive===!0||o.allowMultipleActive===!0;return im(c,d.status==="in_progress"?d.id:void 0,f,g),n_(d,t,f,m),l.metadata.updated_at=m,{changedSteps:[d.id],resultStep:d}}}),a=Z(r.metadata,"standard");return{action:o.op==="plan_complete_step"?"complete-step":o.op==="plan_block_step"?"block-step":"update-step",plan:a,step:i,next_actions:Q(s,a),warnings:[],generated_at:S()}}function ti(e){return cs(e?.trim(),"--step-owner")||void 0}function n_(e,t,n,o){o_(e,t,n),r_(e,t),e.status=n,e.updated_at=o,i_(e,n,o)}function o_(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new p("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",u.USAGE)}function r_(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=ti(t.stepOwner)),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let o=V(t.file).map(Xr),r=V(t.test).map(Zr),i=V(t.doc).map(Qr);o.length>0&&(e.files=Br(e.files,o)),r.length>0&&(e.tests=Br(e.tests,r)),i.length>0&&(e.docs=Br(e.docs,i))}function Br(e,t){let n=[...e??[]],o=new Set(n.map(r=>JSON.stringify(r)));for(let r of t){let i=JSON.stringify(r);o.has(i)||(o.add(i),n.push(r))}return n}function i_(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function s_(e,t,n,o,r){let{document:i,itemId:s,resultStep:a}=await ce({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${o} -> ${r}`,mutator(l){let d=dt(l,o),m=l.filter(g=>g.id!==d.id),f=Math.max(1,Math.min(r,m.length+1));return m.splice(f-1,0,d),m.forEach((g,y)=>{g.order=y+1,g.updated_at=S()}),l.length=0,l.push(...m),{changedSteps:[d.id],resultStep:d}}}),c=Z(i.metadata,"standard");return{action:"reorder-step",plan:c,step:a,next_actions:Q(s,c),warnings:[],generated_at:S()}}async function a_(e,t,n,o){let{document:r,itemId:i,resultStep:s}=await ce({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${o}`,mutator(c){let l=dt(c,o),d=c.filter(m=>m.id!==l.id);return d.forEach((m,f)=>{m.order=f+1}),c.length=0,c.push(...d),{changedSteps:[l.id],resultStep:l}}}),a=Z(r.metadata,"standard");return{action:"remove-step",plan:a,step:s,next_actions:Q(i,a),warnings:[],generated_at:S()}}async function c_(e,t,n,o){let r=ei(t,tm(t.linkKind,"related"));if(r.length===0)throw new p("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",u.USAGE);let i=t.promoteToItemDep===!0,{document:s,itemId:a,resultStep:c}=await ce({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${o}`,mutator(d,m){let f=dt(d,o),g=f.linked_items??[],y=b=>`${b.kind}:${b.id}`,k=new Set(g.map(y));for(let b of r){let v=y(b);k.has(v)||(g.push(b),k.add(v))}if(f.linked_items=g,f.updated_at=S(),i){let b=m.metadata.dependencies??[],v=A=>`${A.kind}:${A.id}`,_=new Set(b.map(v));for(let A of r){let N=A.kind==="depends_on"?"blocked_by":A.kind,O={id:A.id,kind:N,created_at:S(),author:C(t.author,n.settings.author_default)};_.has(v(O))||(b.push(O),_.add(v(O)))}m.metadata.dependencies=b}return{changedSteps:[f.id],resultStep:f}}}),l=Z(s.metadata,"standard");return{action:"link",plan:l,step:c,next_actions:Q(a,l),warnings:[],generated_at:S()}}async function l_(e,t,n,o){let r=te(t.link);if(r.length===0)throw new p("pm plan unlink requires --link <id> to remove",u.USAGE);let{document:i,itemId:s,resultStep:a}=await ce({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${o}`,mutator(l){let d=dt(l,o),m=(d.linked_items??[]).filter(f=>!r.includes(f.id));return d.linked_items=m.length>0?m:void 0,d.updated_at=S(),{changedSteps:[d.id],resultStep:d}}}),c=Z(i.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Q(s,c),warnings:[],generated_at:S()}}async function Wr(e,t,n,o){let r=Gf(o,t);if(!r){let l=`--${o}-text`,d=`--${o}`;throw new p(`pm plan ${o} requires ${l}`,u.USAGE,{code:"missing_required_option",examples:[`pm plan ${o} <plan-id> ${l} "..."`,`pm plan ${o} <plan-id> ${d} "..."`],recovery:{suggested_retry:`pm plan ${o} <plan-id> ${l} <value>`}})}let i=C(t.author,n.settings.author_default),{document:s,itemId:a}=await ce({id:e,options:t,ctx:n,op:`plan_append_${o}`,message:t.message??`plan ${o} append`,mutator(l,d){let m=S();if(o==="decision"){let g=d.metadata.plan_decisions??[];return g.push({ts:m,author:i,decision:r,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),d.metadata.plan_decisions=g,{changedSteps:[]}}if(o==="discovery"){let g=d.metadata.plan_discoveries??[];return g.push({ts:m,author:i,text:r}),d.metadata.plan_discoveries=g,{changedSteps:[]}}let f=d.metadata.plan_validation??[];return f.push({text:r,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),d.metadata.plan_validation=f,{changedSteps:[]}}}),c=Z(s.metadata,"deep");return{action:o,plan:c,next_actions:Q(a,c),warnings:[],generated_at:S()}}async function d_(e,t,n){let o=t.resumeContext?.trim();if(!o)throw new p("pm plan resume requires --resume-context <text>",u.USAGE);let{document:r,itemId:i}=await ce({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=o;let l=t.scope?.trim();return l&&(c.metadata.plan_scope=l),{changedSteps:[]}}}),s=Z(r.metadata,"brief");return{action:"resume",plan:s,next_actions:Q(i,s),warnings:[],generated_at:S()}}async function m_(e,t,n){let o=em(t.mode??"approved","approved"),{document:r,itemId:i}=await ce({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${o}`,mutator(a,c){c.metadata.plan_mode=o;let l=t.scope?.trim();return l&&(c.metadata.plan_scope=l),{changedSteps:[]}}}),s=Z(r.metadata,"brief");return{action:"approve",plan:s,next_actions:Q(i,s),warnings:[],generated_at:S()}}function sm(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function p_(e,t){let n=Z(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Q(e.itemId,n),warnings:sm(t),generated_at:S()}}function u_(e,t,n){let o=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let r of n.linked_items??[]){let i=r.kind==="blocked_by"||r.kind==="blocks"||r.kind==="related"||r.kind==="discovered_from"?r.kind:"related";o.push(`id=${r.id},kind=${i}`)}return o}async function f_(e){let t=[],n={},o=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let r of V(e.options.field)){let i=r.indexOf("=");if(i<=0)throw new p(`Invalid --field entry "${r}"; expected name=value`,u.USAGE);let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(s.length===0)throw new p(`Invalid --field entry "${r}"; expected name=value`,u.USAGE);let c=s.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new p(`Invalid --field entry "${r}"; expected name=value`,u.USAGE);let[l,...d]=c,m=`${l}${d.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(o.has(m))throw new p(`Invalid --field entry "${r}"; "${m}" is reserved by materialize and cannot be overridden`,u.USAGE);n[m]=a}for(let r of e.targets){let i={...n,title:r.title,description:r.body?.trim()||r.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${r.id}`,dep:u_(e.parent,e.planItemId,r)};rm(e.options,i,["description",...Object.keys(n)]);let s=await Ce(i,{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:r.id})}return t}function __(e,t,n){for(let o of t){let r=n.find(a=>a.from_step===o.id);if(!r)continue;let i=e.find(a=>a.id===o.id);if(!i)continue;let s=i.linked_items??[];s.push({id:r.id,kind:"implements",note:`materialized as ${r.type}`}),i.linked_items=s,i.updated_at=S()}}async function h_(e,t,n){let o=te(t.steps);if(o.length===0)throw new p("pm plan materialize requires --steps <ids|orders|all>",u.USAGE);let r=t.materializeType?.trim()||"Task",i=F(n.settings,T()),s=un(r,i);if(!s)throw new p(`Invalid --materialize-type "${r}"`,u.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,l=await om(n,e),d=(l.document.metadata.plan_steps??[]).slice(),{targets:m,skipped:f}=jf(d,o);if(m.length===0){if(f.length>0)return p_(l,f);throw new p("No matching plan steps found for --steps",u.NOT_FOUND)}let g=await f_({targets:m,parent:a,planItemId:l.itemId,resolvedTypeName:s,tags:c,options:t,pmRoot:n.pmRoot}),{document:y,itemId:k}=await ce({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${o.join(",")}`,mutator(v){return __(v,m,g),{changedSteps:m.map(_=>_.id)}}}),b=Z(y.metadata,"standard");return{action:"materialize",plan:b,materialized:g,...f.length>0?{materialize_skipped:f}:{},next_actions:Q(k,b),warnings:sm(f),generated_at:S()}}function g_(e){if(e.subcommand==="create")return e;let t=Qd(e.options.step);if(t.length>1)throw new p(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,u.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:le(e.options,{...e.options,stepTitle:t[0]})}:e}function ge(e,t){if(!e.id)throw new p(`pm plan ${t} requires a plan id`,u.USAGE);return e.id}function He(e,t){let n=ge(e,t);if(!e.stepRef)throw new p(`pm plan ${t} requires <plan-id> <step>`,u.USAGE);return{id:n,stepRef:e.stepRef}}function y_(e){let t=He(e,"reorder-step");if(e.reorderTo===void 0)throw new p("pm plan reorder-step requires <plan-id> <step> <new-order>",u.USAGE);return{...t,reorderTo:e.reorderTo}}var b_={create:(e,t)=>Xf(e.options,e.global,t),show:(e,t)=>Zf(ge(e,"show"),e.options,t),"add-step":(e,t)=>e_(ge(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=He(e,"update-step");return Hr(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=He(e,"complete-step");return Hr(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=He(e,"block-step");return Hr(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=y_(e);return s_(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=He(e,"remove-step");return a_(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=He(e,"link");return c_(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=He(e,"unlink");return l_(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Wr(ge(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Wr(ge(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Wr(ge(e,"validation"),e.options,t,"validation"),resume:(e,t)=>d_(ge(e,"resume"),e.options,t),approve:(e,t)=>m_(ge(e,"approve"),e.options,t),materialize:(e,t)=>h_(ge(e,"materialize"),e.options,t)};function w_(e){let t=b_[e];if(!t)throw ae({command_path:"plan",token:e,allowed:Tf});return t}async function am(e){let t=await zf(e.global),n=g_(e),o=await w_(n.subcommand)(n,t);return o.action==="show"?o:{...o,mutation_receipt:oo(o,t.pmRoot)}}var lm=2,oi="update-many",v_=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),k_=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),S_={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},A_=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],dm=e=>{let t={};for(let[n,o]of Object.entries(e))v_.has(n)||o!==void 0&&(t[n]=o);return t},x_=e=>Object.keys(dm(e)).length>0,mm=e=>typeof e=="string"?e.trim():e,I_=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},ni=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},E_=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??mm(e)},C_={priority:I_,estimatedMinutes:ni,order:ni,rank:ni,regression:E_},R_=(e,t)=>{if(t!==void 0)return(C_[e]??mm)(t)},ro=(e,t)=>J(e,t),T_=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],O_=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,$_=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",cm=(e,t)=>t===void 0?void 0:e[t],mt=e=>Array.isArray(e)?e.length:0,F_=(e,t,n)=>{let o=n[e.addKey],r=cm(n,e.removeKey),i=mt(o),s=mt(r),a=n[e.clearKey]===!0,c=cm(n,e.replaceKey)===!0;if(![a,c,i>0,s>0].includes(!0))return;let l=T_(e.field,t[e.field]);return{field:e.field,before:l,after:{operation:$_({replace:c,clear:a,removeCount:s}),clear:a,replace:c,add_count:i,remove_count:s,before_count:O_(e.field,l)}}},P_=(e,t)=>{let n=[];for(let o of A_){let r=F_(o,e,t);r!==void 0&&n.push(r)}return n},N_=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],L_=(e,t)=>{if(![t.tags!==void 0,mt(t.addTags)>0,mt(t.removeTags)>0].includes(!0))return;let n=N_(e.tags),o=t.tags===void 0?n:$t(t.tags),r=es(o,t.addTags),i=ts(r,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),s=n.slice().sort((a,c)=>a.localeCompare(c));if(!ro(s,i))return{field:"tags",before:n,after:i}},M_=(e,t)=>{let n=e.acceptance_criteria,o=Qi(Zi(n),t.addAc,t.removeAc);if(o.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,u.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals});let r=o.criteria.join("; ");if(!ro(typeof n=="string"?n:"",r))return{field:"acceptance_criteria",before:n,after:r}},D_=(e,t,n)=>{for(let[o,r]of Object.entries(S_)){let i=n[o];if(i===void 0)continue;let s=t[r],a=R_(o,i);ro(s,a)||e.push({field:r,before:s,after:a})}},j_=(e,t,n,o)=>{let r=vs(n,o,["update_many"]);for(let[i,s]of Object.entries(r)){let a=t[i];ro(a,s)||e.push({field:i,before:a,after:s})}},G_=(e,t,n,o)=>{if(n===void 0||n.length===0)return;let r=fr(n,o,ue(T()),["update_many"]);for(let i of r){let s=t[i];s!==void 0&&e.push({field:i,before:s,after:null})}},U_=(e,t,n={})=>{let o=e,r=[],i=L_(o,n);if(i&&r.push(i),D_(r,o,n),mt(n.addAc)>0||mt(n.removeAc)>0){let s=M_(o,n);s!==void 0&&r.push(s)}return r.push(...P_(o,n)),j_(r,o,n,t),G_(r,o,n.unset,t),{id:e.id,changes:r}},q_=(e,t)=>ra(e,t,{strict:!0,flagLabel:"--filter-status"}),z_=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)},H_=[({update:e})=>{e.priority!==void 0&&In(e.priority)},({update:e,settings:t})=>{e.unset!==void 0&&e.unset.length>0&&fr(e.unset,Xe(t.schema),ue(T()),["update_many"])},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let o=F(t,T());if(!un(e.type,o))throw new p(ca(e.type,o.types,bs(n,t.schema)),u.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!Ne(e.status,t)){let n=t.definitions.map(o=>o.id);throw new p(`Invalid status value "${e.status}". Allowed: ${n.join(", ")}`,u.USAGE,{code:"invalid_argument_value",field:"status",value:e.status,allowed:n})}},({update:e})=>{e.deadline!==void 0&&us(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&ss(e.estimatedMinutes,"estimated-minutes")}],B_=(e,t,n,o)=>{let r={update:e,settings:t,statusRegistry:n,pmRoot:o};for(let i of H_)i(r)},W_=async e=>{let t=await yn(e.pmRoot,oi,e.rollbackId,lm),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,o=await to(e.pmRoot,t,{author:e.options.update?.author,message:n,force:e.options.update?.force}),r=o.rows.filter(i=>i.status==="skipped").length;return{...je({applied:o.restored_ids.length,skipped:r,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:o.restored_ids.length,skipped_count:r,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}},V_=async e=>{let t={schema_version:lm,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await gn(e.pmRoot,oi,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},K_=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(r=>r.trim()).filter(r=>r.length>0))],o=new Set(t.map(r=>r.id));return n.filter(r=>!o.has(r))},ri=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},J_=async e=>{let t=x(process.cwd(),e.path);await P(t);let n=await I(t);return{pmRoot:t,settings:n,statusRegistry:W(n.schema),runtimeFieldRegistry:Xe(n.schema)}},Y_=e=>{if(e.options.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(Jt(e.options.list,e.options.status))throw new p("Rollback mode does not accept filter options",u.USAGE);if(Object.keys(e.updateSummary).length>0)throw new p("Rollback mode does not accept update mutation flags",u.USAGE);return W_({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},X_=async e=>{q_(e.options.status,e.runtime.statusRegistry);let t=await _e(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(r=>{let i=U_(r,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),o=e.options.list?.ids==null?[]:(await _e(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(r=>r.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:K_(e.options.list?.ids,o)}},Z_=e=>({outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...ri(e)}),Q_=e=>({...je({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...ri(e)}),eh=async e=>{let t=[],n=[],o=e.options.update.message??`update-many apply ${e.checkpointId}`,r=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!r.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let s=Ao(le(e.options.update,{...e.options.update,message:o,runtimeFieldCommands:["update_many"]})),a=await Tn({pmRoot:e.pmRoot,itemId:i.id,checkpointId:e.checkpointId},()=>lt(i.id,s,e.global));t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(s){let a=await Kn(s,i.id,e.pmRoot);if(a!==void 0){t.push({id:i.id,status:"updated",...a}),n.push(i.id);continue}t.push({id:i.id,status:"failed",error:Ae(s),...await ot(s,e.pmRoot)})}}return{rows:t,updatedIds:n}},th=async e=>{if(e.plan.actionable.length===0)return Q_(e.plan);let t=S(),n=hn(oi,t),o=new Set(e.plan.actionable.map(m=>m.id)),r=e.plan.listed.items.filter(m=>o.has(m.id)).map(m=>({id:m.id,target_updated_at:m.updated_at})),i=e.options.checkpoint===!1?void 0:await V_({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:r}),s=await eh({pmRoot:e.runtime.pmRoot,items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=m=>s.rows.filter(f=>f.status===m).length,c=a("updated"),l=a("skipped"),d=a("failed");return{...je({applied:c,skipped:l,failed:d,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:l,failed_count:d,rows:s.rows,ids:s.updatedIds,...ri(e.plan)}},pm=async(e,t)=>{let n=_n(e.rollback),o=await J_(t);n===void 0&&(e={...e,update:Ao(await Ql(e.update))});let r=dm(e.update);if(z_(e.list),n!==void 0)return Y_({runtime:o,rollbackId:n,options:e,global:t,updateSummary:r});if(!x_(e.update)&&e.dryRun!==!0)throw new p(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${k_}), or pass --dry-run for a filter-only preview.`,u.USAGE);B_(e.update,o.settings,o.statusRegistry,o.pmRoot),ed(e.update);let i=await pr({pmRoot:o.pmRoot,dependencies:_r(e.update.dep,o.settings.id_prefix,S(),C(e.update.author,o.settings.author_default)).additions,idPrefix:o.settings.id_prefix,itemFormat:o.settings.item_format,typeToFolder:F(o.settings,T()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),s=await X_({options:e,global:t,runtime:o,updateSummary:r,dependencyWarnings:i});return await pr({pmRoot:o.pmRoot,dependencies:_r(e.update.dep,o.settings.id_prefix,S(),C(e.update.author,o.settings.author_default)).additions,idPrefix:o.settings.id_prefix,itemFormat:o.settings.item_format,typeToFolder:F(o.settings,T()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:s.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:o.settings.schema}),e.dryRun===!0?Z_(s):th({runtime:o,options:e,global:t,plan:s})};function nh(e){if(e===void 0)return;if(e.trim().length===0)throw new p("--add-json must contain a JSON value",u.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new p("--add-json must be valid JSON",u.USAGE,{code:"structured_event_json_invalid"})}return t}function oh(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function rh(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new p("--since must be a valid ISO timestamp",u.USAGE,{code:"structured_event_since_invalid"});return t}function um(e){return Object.prototype.toString.call(e)==="[object Object]"?e:{}}async function fm(e,t,n){let o=nh(t.addJson),r=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(o!==void 0&&r)throw new p("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",u.USAGE,{code:"structured_event_input_conflict"});let i=o===void 0?void 0:Ot(o),s=[t.since,t.eventType].some(y=>y!==void 0),a=rh(t.since),c=ia(t.limit),l=await it(e,{...t,...s?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,s].includes(!0)},n,{input:await Ln(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:y=>rt(y),createEntry:y=>o===void 0?y:{...y,format:"json",data:o,event_type:oh(o)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm notes --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}}),d=t.eventType?.trim(),m=l.notes.filter(y=>{let k=um(y),b=[k.format==="json",k.data!==void 0].every(Boolean),v=[a===void 0,Date.parse(k.created_at??"")>=(a??Number.POSITIVE_INFINITY)].includes(!0),_=[!d,k.event_type===d].includes(!0);return[!s,[b,v,_].every(Boolean)].includes(!0)}),f=s?Ec(m,c):m,g=f.filter(y=>um(y).format==="json").length;return{...l,notes:f,count:f.length,...s?{total_count:m.length,returned_count:f.length,has_more:f.length<m.length,...c===void 0?{}:{limit:c},structured_event_count:g}:t.includeMeta===!0?{structured_event_count:g}:{}}}import Ih from"node:path";var pt=["agile","ops","research"],ii={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:Un.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
12
12
 
13
13
  ## I want
14
14
 
@@ -32,7 +32,7 @@ import{$c as ed,$d as wd,Fa as Jc,Fb as Gl,Ga as Gn,H as Wc,I as Vc,Ib as Ul,Jb
32
32
  ## Results
33
33
 
34
34
  ## Conclusion
35
- `}}],packages:[{spec:"search-advanced",reason:"Semantic retrieval over experiments and findings."},{spec:"templates",reason:"Consistent experiment and hypothesis scaffolds."},{spec:"beads",reason:"Import structured prior work into the tracker."}]}};function oh(e){if(e===void 0)return;let t=Re(e);if(t.length===0)throw new Error("Profile name must not be empty.");if(pt.includes(t))return t;throw new Error(`Invalid profile "${e}". Allowed: ${pt.join(", ")}.`)}function sk(e){let t=oh(e);if(t===void 0)throw new Error(`Profile name is required. Allowed: ${pt.join(", ")}.`);return ii[t]}function ak(){return pt.map(e=>ii[e])}function Re(e){return e.trim().toLowerCase().replaceAll("-","_")}function fm(e){return e.map(t=>t.definition.name).join(", ")}function si(e=[]){let t=pt.map(i=>({definition:ii[i],source:"builtin"})),n=new Set(pt.map(i=>Re(i))),o=new Set(n),r=[];for(let i of e){let s=Re(i.profile.name);if(n.has(s)){r.push(`Extension "${i.name}" profile "${i.profile.name}" uses a name reserved by a built-in archetype and was ignored.`);continue}if(o.has(s)){r.push(`Profile "${i.profile.name}" from extension "${i.name}" duplicates an already-registered profile and was ignored.`);continue}o.add(s),t.push({definition:i.profile,source:"extension",package:i.name})}return{profiles:t,warnings:r}}function io(e,t=[]){let{profiles:n,warnings:o}=si(t);if(typeof e!="string"||e.trim().length===0)throw new Error(`Profile name is required. Allowed: ${fm(n)}.`);let r=Re(e),i=n.find(s=>Re(s.definition.name)===r);if(i===void 0)throw new Error(`Invalid profile "${e}". Allowed: ${fm(n)}.`);return{resolved:i,warnings:o}}function ci(e){return{types:e.types.length,statuses:e.statuses.length,fields:e.fields.length,workflows:e.workflows.length,config:e.config.length,templates:e.templates.length,packages:e.packages.length}}function _m(e){return{name:e.name,title:e.title,summary:e.summary,composition:ci(e),types:e.types.map(t=>ai(()=>ue(t).name,()=>String(t.name??""))),statuses:e.statuses.map(t=>ai(()=>Ge(t).id,()=>String(t.id??""))),fields:e.fields.map(t=>ai(()=>fe(t).key,()=>String(t.key??""))),workflows:e.workflows.map(t=>t.type),config:e.config.map(t=>`${t.key}=${t.value}`),templates:e.templates.map(t=>t.name),packages:e.packages.map(t=>({spec:t.spec,reason:t.reason}))}}function ai(e,t){try{return e()}catch{return t()}}var Ak=["profile","types","statuses","fields","workflows","config","templates","packages"],xk=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","field_option_collision","field_flag_invalid","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],rh=new Set(_s.flatMap(e=>[Ye(e.id),...(e.aliases??[]).map(t=>Ye(t))]).filter(e=>e.length>0)),hm=new Set(Pt.map(e=>e.toLowerCase()));function ih(e,t){e.name.trim().length===0?t.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):e.name!==Re(e.name)&&t.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:e.name,message:`Profile name "${e.name}" is not in canonical form; resolution folds it to "${Re(e.name)}" (lowercase, hyphens as underscores).`}),e.title.trim().length===0&&t.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),e.summary.trim().length===0&&t.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function sh(e,t){let n=new Set,o=new Set;for(let[r,i]of e.types.entries()){let s;try{s=ue(i).name}catch(c){t.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof i.name=="string"?i.name:`#${r}`,message:Ae(c)});continue}let a=s.toLowerCase();if(o.has(a)){t.push({severity:"error",code:"type_duplicate",dimension:"types",target:s,message:`Item type "${s}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(a),n.add(a)}return n}function ah(e,t){let n=new Set,o=new Set;for(let[r,i]of e.statuses.entries()){let s;try{s=Ge(i)}catch(a){t.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof i.id=="string"?i.id:`#${r}`,message:Ae(a)});continue}if(o.has(s.id)){t.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:s.id,message:`Status "${s.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(s.id),n.add(s.id);for(let a of s.aliases??[])n.add(Ye(a))}return n}function ch(e,t){let n=new Set;for(let[o,r]of e.fields.entries()){let i,s;try{s=fe(r),i=s.key}catch(d){t.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof r.key=="string"?r.key:`#${o}`,message:Ae(d)});continue}if(n.has(i)){t.push({severity:"error",code:"field_duplicate",dimension:"fields",target:i,message:`Field "${i}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}n.add(i);let a=vc(s);a.length>0&&t.push({severity:"error",code:"field_flag_invalid",dimension:"fields",target:i,message:`Field "${i}" declares a flag that is not one option spelling: ${a.map(kc).join("; ")}. Pass one spelling per alias.`});let c=wc(s);c.length>0&&t.push({severity:"error",code:"field_option_collision",dimension:"fields",target:i,message:`Field "${i}" would disable a built-in option: ${c.map(Sc).join("; ")}. Rename the field or narrow its commands.`});let l=Tc(i);l&&t.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:i,message:`Field "${i}" collides with canonical MCP property "${l.property}" owned by ${l.owner}; callers must pass the custom value through ${l.nested_path}.`})}}function lh(e,t,n,o){let r=new Set;for(let[i,s]of e.workflows.entries()){let a=s.type.trim().toLowerCase();if(a.length===0){o.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${i}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}let c=r.has(a);r.add(a),c?o.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:s.type,message:`Workflow type "${s.type}" is declared more than once; the later transition set wins.`}):!hm.has(a)&&!t.has(a)&&o.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:s.type,message:`Workflow governs type "${s.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});let l=new Set;for(let d of s.allowed_transitions){let m=Ye(d[0]),f=Ye(d[1]);if(m.length===0||f.length===0){o.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:s.type,message:`Workflow "${s.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(let g of[m,f])rh.has(g)||n.has(g)||l.has(g)||(l.add(g),o.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:g,message:`Workflow "${s.type}" references status "${g}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function dh(e,t){let n=new Set;for(let o of e.config){let r=ct(o.key);if(r===void 0){t.push({severity:"error",code:"config_key_unknown",dimension:"config",target:o.key,message:`Config knob "${o.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}n.has(r.key)?t.push({severity:"error",code:"config_duplicate",dimension:"config",target:r.key,message:`Config knob "${r.key}" is set more than once; the later value silently overwrites the earlier one.`}):n.add(r.key);let i=Hn(r,o.value);i.ok||t.push({severity:"error",code:"config_value_invalid",dimension:"config",target:o.key,message:i.error.message})}}function mh(e,t,n){for(let o of e.templates){let r=o.options.type;if(typeof r!="string"||r.trim().length===0)continue;let i=r.trim().toLowerCase();!hm.has(i)&&!t.has(i)&&n.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:o.name,message:`Template "${o.name}" creates type "${r}" which is neither a built-in type nor declared by this profile.`})}}function ph(e,t){for(let[n,o]of e.packages.entries())o.spec.trim().length===0&&t.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${n}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function gm(e){let t=[];ih(e,t);let n=sh(e,t),o=ah(e,t);ch(e,t),lh(e,n,o,t),dh(e,t),mh(e,n,t),ph(e,t);let r=t.filter(s=>s.severity==="error").length,i=t.length-r;return{profile:e.name,ok:r===0,findings:t,errorCount:r,warningCount:i}}function li(e,t,n,o,r){let i=e,s=[];for(let a of t){let c=o(i),l=r(i,a),d=o(l.file);i=l.file;let m=c===d?"unchanged":l.replaced?"update":"add";s.push({key:n(a),status:m})}return{file:i,changes:s,changed:s.some(a=>a.status!=="unchanged")}}function ym(e){return JSON.stringify(e.map(t=>t.join("\0")).sort())}function uh(e,t){let n=e.map(r=>({...r})),o=[];for(let r of t){let i=n.findIndex(a=>a.type===r.type),s={type:r.type,allowed_transitions:r.allowed_transitions};i<0?(n.push(s),o.push({type:r.type,status:"add"})):ym(n[i].allowed_transitions)===ym(r.allowed_transitions)?o.push({type:r.type,status:"unchanged"}):(n[i]=s,o.push({type:r.type,status:"update"}))}return{changes:o,result:n,changed:o.some(r=>r.status!=="unchanged")}}function fh(e,t){let n=[];for(let o of e.config){let r=ct(o.key);if(r===void 0)throw new Error(`Profile "${e.name}" references unknown config key "${o.key}".`);let i=Hn(r,o.value);if(!i.ok)throw new Error(`Profile "${e.name}" config ${o.key}: ${i.error.message}`);let s=wl(t,r),a=s===null?"add":s===i.parsed.value?"unchanged":"update";n.push({key:r.key,path:r.path,value:i.parsed.value,status:a})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function bm(e){let t=Object.entries(e).sort(([n],[o])=>n.localeCompare(o));return JSON.stringify(t)}function _h(e,t){let n=[];for(let o of e.templates){let r=t.get(o.name),i;r===void 0?i="add":bm(r)===bm(o.options)?i="unchanged":i="update",n.push({name:o.name,options:o.options,status:i})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function wm(e,t){let n=li(ra(t.typesRaw),e.types,d=>ue(d).name,In,(d,m)=>ia(d,ue(m))),o=li(Zc(t.statusesRaw),e.statuses,d=>Ge(d).id,qn,(d,m)=>Qc(d,Ge(m))),r=li(yc(t.fieldsRaw),e.fields,d=>fe(d).key,Nn,(d,m)=>bc(d,fe(m))),i=uh(t.workflows,e.workflows),s=fh(e,t.settings),a=_h(e,t.templates),c=e.packages.map(d=>({spec:d.spec,reason:d.reason,status:t.installedPackages.has(d.spec)?"installed":"recommended"})),l=n.changed||o.changed||r.changed||i.changed||s.changed||a.changed;return{profile:{name:e.name,title:e.title,summary:e.summary},types:n,statuses:o,fields:r,workflows:i,config:s,templates:a,packages:c,changed:l}}import km from"node:fs/promises";import Sm from"node:path";var hh="templates",di=".json",Am=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,gh=Rc.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),yh=new Set(gh),vm="1970-01-01T00:00:00.000Z",xm={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
35
+ `}}],packages:[{spec:"search-advanced",reason:"Semantic retrieval over experiments and findings."},{spec:"templates",reason:"Consistent experiment and hypothesis scaffolds."},{spec:"beads",reason:"Import structured prior work into the tracker."}]}};function ih(e){if(e===void 0)return;let t=Re(e);if(t.length===0)throw new Error("Profile name must not be empty.");if(pt.includes(t))return t;throw new Error(`Invalid profile "${e}". Allowed: ${pt.join(", ")}.`)}function ck(e){let t=ih(e);if(t===void 0)throw new Error(`Profile name is required. Allowed: ${pt.join(", ")}.`);return ii[t]}function lk(){return pt.map(e=>ii[e])}function Re(e){return e.trim().toLowerCase().replaceAll("-","_")}function _m(e){return e.map(t=>t.definition.name).join(", ")}function si(e=[]){let t=pt.map(i=>({definition:ii[i],source:"builtin"})),n=new Set(pt.map(i=>Re(i))),o=new Set(n),r=[];for(let i of e){let s=Re(i.profile.name);if(n.has(s)){r.push(`Extension "${i.name}" profile "${i.profile.name}" uses a name reserved by a built-in archetype and was ignored.`);continue}if(o.has(s)){r.push(`Profile "${i.profile.name}" from extension "${i.name}" duplicates an already-registered profile and was ignored.`);continue}o.add(s),t.push({definition:i.profile,source:"extension",package:i.name})}return{profiles:t,warnings:r}}function io(e,t=[]){let{profiles:n,warnings:o}=si(t);if(typeof e!="string"||e.trim().length===0)throw new Error(`Profile name is required. Allowed: ${_m(n)}.`);let r=Re(e),i=n.find(s=>Re(s.definition.name)===r);if(i===void 0)throw new Error(`Invalid profile "${e}". Allowed: ${_m(n)}.`);return{resolved:i,warnings:o}}function ci(e){return{types:e.types.length,statuses:e.statuses.length,fields:e.fields.length,workflows:e.workflows.length,config:e.config.length,templates:e.templates.length,packages:e.packages.length}}function hm(e){return{name:e.name,title:e.title,summary:e.summary,composition:ci(e),types:e.types.map(t=>ai(()=>fe(t).name,()=>String(t.name??""))),statuses:e.statuses.map(t=>ai(()=>Ge(t).id,()=>String(t.id??""))),fields:e.fields.map(t=>ai(()=>pe(t).key,()=>String(t.key??""))),workflows:e.workflows.map(t=>t.type),config:e.config.map(t=>`${t.key}=${t.value}`),templates:e.templates.map(t=>t.name),packages:e.packages.map(t=>({spec:t.spec,reason:t.reason}))}}function ai(e,t){try{return e()}catch{return t()}}var Ik=["profile","types","statuses","fields","workflows","config","templates","packages"],Ek=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","field_option_collision","field_flag_invalid","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],sh=new Set(gs.flatMap(e=>[Ye(e.id),...(e.aliases??[]).map(t=>Ye(t))]).filter(e=>e.length>0)),gm=new Set(Pt.map(e=>e.toLowerCase()));function ah(e,t){e.name.trim().length===0?t.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):e.name!==Re(e.name)&&t.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:e.name,message:`Profile name "${e.name}" is not in canonical form; resolution folds it to "${Re(e.name)}" (lowercase, hyphens as underscores).`}),e.title.trim().length===0&&t.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),e.summary.trim().length===0&&t.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function ch(e,t){let n=new Set,o=new Set;for(let[r,i]of e.types.entries()){let s;try{s=fe(i).name}catch(c){t.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof i.name=="string"?i.name:`#${r}`,message:Ae(c)});continue}let a=s.toLowerCase();if(o.has(a)){t.push({severity:"error",code:"type_duplicate",dimension:"types",target:s,message:`Item type "${s}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(a),n.add(a)}return n}function lh(e,t){let n=new Set,o=new Set;for(let[r,i]of e.statuses.entries()){let s;try{s=Ge(i)}catch(a){t.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof i.id=="string"?i.id:`#${r}`,message:Ae(a)});continue}if(o.has(s.id)){t.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:s.id,message:`Status "${s.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(s.id),n.add(s.id);for(let a of s.aliases??[])n.add(Ye(a))}return n}function dh(e,t){let n=new Set;for(let[o,r]of e.fields.entries()){let i,s;try{s=pe(r),i=s.key}catch(d){t.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof r.key=="string"?r.key:`#${o}`,message:Ae(d)});continue}if(n.has(i)){t.push({severity:"error",code:"field_duplicate",dimension:"fields",target:i,message:`Field "${i}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}n.add(i);let a=vc(s,r);a.length>0&&t.push({severity:"error",code:"field_flag_invalid",dimension:"fields",target:i,message:`Field "${i}" declares a flag that is not one option spelling: ${a.map(kc).join("; ")}. Pass one spelling per alias.`});let c=wc(s);c.length>0&&t.push({severity:"error",code:"field_option_collision",dimension:"fields",target:i,message:`Field "${i}" would disable a built-in option: ${c.map(Sc).join("; ")}. Rename the field or narrow its commands.`});let l=Tc(i);l&&t.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:i,message:`Field "${i}" collides with canonical MCP property "${l.property}" owned by ${l.owner}; callers must pass the custom value through ${l.nested_path}.`})}}function mh(e,t,n,o){let r=new Set;for(let[i,s]of e.workflows.entries()){let a=s.type.trim().toLowerCase();if(a.length===0){o.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${i}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}let c=r.has(a);r.add(a),c?o.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:s.type,message:`Workflow type "${s.type}" is declared more than once; the later transition set wins.`}):!gm.has(a)&&!t.has(a)&&o.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:s.type,message:`Workflow governs type "${s.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});let l=new Set;for(let d of s.allowed_transitions){let m=Ye(d[0]),f=Ye(d[1]);if(m.length===0||f.length===0){o.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:s.type,message:`Workflow "${s.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(let g of[m,f])sh.has(g)||n.has(g)||l.has(g)||(l.add(g),o.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:g,message:`Workflow "${s.type}" references status "${g}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function ph(e,t){let n=new Set;for(let o of e.config){let r=ct(o.key);if(r===void 0){t.push({severity:"error",code:"config_key_unknown",dimension:"config",target:o.key,message:`Config knob "${o.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}n.has(r.key)?t.push({severity:"error",code:"config_duplicate",dimension:"config",target:r.key,message:`Config knob "${r.key}" is set more than once; the later value silently overwrites the earlier one.`}):n.add(r.key);let i=Hn(r,o.value);i.ok||t.push({severity:"error",code:"config_value_invalid",dimension:"config",target:o.key,message:i.error.message})}}function uh(e,t,n){for(let o of e.templates){let r=o.options.type;if(typeof r!="string"||r.trim().length===0)continue;let i=r.trim().toLowerCase();!gm.has(i)&&!t.has(i)&&n.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:o.name,message:`Template "${o.name}" creates type "${r}" which is neither a built-in type nor declared by this profile.`})}}function fh(e,t){for(let[n,o]of e.packages.entries())o.spec.trim().length===0&&t.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${n}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function ym(e){let t=[];ah(e,t);let n=ch(e,t),o=lh(e,t);dh(e,t),mh(e,n,o,t),ph(e,t),uh(e,n,t),fh(e,t);let r=t.filter(s=>s.severity==="error").length,i=t.length-r;return{profile:e.name,ok:r===0,findings:t,errorCount:r,warningCount:i}}function li(e,t,n,o,r){let i=e,s=[];for(let a of t){let c=o(i),l=r(i,a),d=o(l.file);i=l.file;let m=c===d?"unchanged":l.replaced?"update":"add";s.push({key:n(a),status:m})}return{file:i,changes:s,changed:s.some(a=>a.status!=="unchanged")}}function bm(e){return JSON.stringify(e.map(t=>t.join("\0")).sort())}function _h(e,t){let n=e.map(r=>({...r})),o=[];for(let r of t){let i=n.findIndex(a=>a.type===r.type),s={type:r.type,allowed_transitions:r.allowed_transitions};i<0?(n.push(s),o.push({type:r.type,status:"add"})):bm(n[i].allowed_transitions)===bm(r.allowed_transitions)?o.push({type:r.type,status:"unchanged"}):(n[i]=s,o.push({type:r.type,status:"update"}))}return{changes:o,result:n,changed:o.some(r=>r.status!=="unchanged")}}function hh(e,t){let n=[];for(let o of e.config){let r=ct(o.key);if(r===void 0)throw new Error(`Profile "${e.name}" references unknown config key "${o.key}".`);let i=Hn(r,o.value);if(!i.ok)throw new Error(`Profile "${e.name}" config ${o.key}: ${i.error.message}`);let s=wl(t,r),a=s===null?"add":s===i.parsed.value?"unchanged":"update";n.push({key:r.key,path:r.path,value:i.parsed.value,status:a})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function wm(e){let t=Object.entries(e).sort(([n],[o])=>n.localeCompare(o));return JSON.stringify(t)}function gh(e,t){let n=[];for(let o of e.templates){let r=t.get(o.name),i;r===void 0?i="add":wm(r)===wm(o.options)?i="unchanged":i="update",n.push({name:o.name,options:o.options,status:i})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function vm(e,t){let n=li(sa(t.typesRaw),e.types,d=>fe(d).name,En,(d,m)=>aa(d,fe(m))),o=li(Zc(t.statusesRaw),e.statuses,d=>Ge(d).id,qn,(d,m)=>Qc(d,Ge(m))),r=li(_s(t.fieldsRaw),e.fields,d=>pe(d).key,bn,(d,m)=>hs(d,pe(m))),i=_h(t.workflows,e.workflows),s=hh(e,t.settings),a=gh(e,t.templates),c=e.packages.map(d=>({spec:d.spec,reason:d.reason,status:t.installedPackages.has(d.spec)?"installed":"recommended"})),l=n.changed||o.changed||r.changed||i.changed||s.changed||a.changed;return{profile:{name:e.name,title:e.title,summary:e.summary},types:n,statuses:o,fields:r,workflows:i,config:s,templates:a,packages:c,changed:l}}import Sm from"node:fs/promises";import Am from"node:path";var yh="templates",di=".json",xm=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,bh=Rc.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),wh=new Set(bh),km="1970-01-01T00:00:00.000Z",Im={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
36
36
  1.
37
37
  2.
38
38
  3.
@@ -56,29 +56,29 @@ import{$c as ed,$d as wd,Fa as Jc,Fb as Gl,Ga as Gn,H as Wc,I as Vc,Ib as Ul,Jb
56
56
  `},chore:{type:"Chore",priority:"3",tags:"chore",acceptanceCriteria:"Maintenance task done with no behavior change and green checks.",body:`## What
57
57
 
58
58
  ## Why
59
- `}},Bk={normalizeTemplateName:so,extractTemplateOptions:Im,parseStoredTemplateDocument:fi,builtinTemplateDocument:Em,readStoredTemplateDocument:Rm};function so(e){let t=e.trim();if(!Am.test(t))throw new p(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,u.USAGE);return t}function mi(e){return Sm.join(e,hh)}function ao(e,t){return Sm.join(mi(e),`${t}${di}`)}async function pi(e){await P(e)}function ui(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Im(e){let t={};for(let[n,o]of Object.entries(e))if(o!==void 0){if(n==="priority"){t[n]=String(xn(o));continue}if(yh.has(n)){if(typeof o=="string"){t[n]=[o];continue}if(!Array.isArray(o))continue;let r=o.filter(i=>typeof i=="string");r.length>0&&(t[n]=r);continue}if(typeof o=="string"){t[n]=o;continue}Array.isArray(o)&&o.every(r=>typeof r=="string")&&(t[n]=[...o])}return ui(t)}function bh(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(`Template "${t}" has invalid options payload.`,u.GENERIC_FAILURE);let n=e,o={};for(let[r,i]of Object.entries(n)){let s=r.trim();if(s.length===0)throw new p(`Template "${t}" contains an empty option key.`,u.GENERIC_FAILURE);if(typeof i=="string"){o[s]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){o[s]=[...i];continue}throw new p(`Template "${t}" contains invalid value for option "${s}".`,u.GENERIC_FAILURE)}return ui(o)}function fi(e,t){let n;try{n=JSON.parse(e)}catch{throw new p(`Template "${t}" contains invalid JSON.`,u.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Template "${t}" has invalid document shape.`,u.GENERIC_FAILURE);let o=n,r=bh(o.options,t),i=S();return{name:typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():t,created_at:typeof o.created_at=="string"?o.created_at:i,updated_at:typeof o.updated_at=="string"?o.updated_at:i,options:r}}function Em(e){let t=xm[e];return t?{name:e,created_at:vm,updated_at:vm,options:ui({...t})}:null}async function Cm(e,t){let n=await de(ao(e,t));if(n!==null)return{document:fi(n,t),source:"user"};let o=Em(t);if(o)return{document:o,source:"builtin"};throw new p(`Template "${t}" not found`,u.NOT_FOUND)}async function Rm(e,t){let n=await de(ao(e,t));if(n===null)throw new p(`Template "${t}" not found`,u.NOT_FOUND);return fi(n,t)}async function wh(e,t){let n=so(t),{document:o}=await Cm(e,n);return o.options}async function _i(e,t,n){let o=x(process.cwd(),n.path);await pi(o);let r=so(e),i=Im(t);if(Object.keys(i).length===0)throw new p("templates save requires at least one create option flag",u.USAGE);let s=S(),a=ao(o,r),c=s;await ke(a)&&(c=(await Rm(o,r)).created_at);let l={name:r,created_at:c,updated_at:s,options:i},d=await I(o);return await km.mkdir(mi(o),{recursive:!0}),await tt({pmRoot:o,filePath:a,raw:`${JSON.stringify(l,null,2)}
60
- `,op:"templates:save",author:C(void 0,d.author_default),lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms}),{name:l.name,created_at:l.created_at,updated_at:l.updated_at,path:a,options:l.options}}async function vh(e){let t=mi(e);return await ke(t)?(await km.readdir(t)).filter(o=>o.toLowerCase().endsWith(di)).map(o=>o.slice(0,-di.length)).filter(o=>Am.test(o)):[]}async function kh(e){let t=x(process.cwd(),e.path);await pi(t);let n=await vh(t),o=new Set(n),r=Object.keys(xm).filter(c=>!o.has(c)),i=[...n].sort((c,l)=>c.localeCompare(l)),s=[...r].sort((c,l)=>c.localeCompare(l)),a=[...new Set([...i,...s])].sort((c,l)=>c.localeCompare(l));return{templates:a,count:a.length,builtin_templates:s,user_templates:i}}async function Sh(e,t){let n=x(process.cwd(),t.path);await pi(n);let o=so(e),{document:r,source:i}=await Cm(n,o);return{name:r.name,source:i,created_at:r.created_at,updated_at:r.updated_at,path:i==="builtin"?`builtin:${o}`:ao(n,o),options:r.options}}var Fm=["list","show","apply","lint"],xh="schema-types",Ih="schema-statuses",Eh="schema-fields";function co(){let e=T();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Pm(){let{profiles:e,warnings:t}=si(co());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:ci(n.definition)})),warnings:t,generated_at:S()}}function Nm(e){let t;try{t=io(e,co())}catch(o){throw new p(o instanceof Error?o.message:String(o),u.USAGE)}let{resolved:n}=t;return{action:"show",..._m(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Lm(e){let t;try{t=io(e,co())}catch(r){throw new p(r instanceof Error?r.message:String(r),u.USAGE)}let{resolved:n}=t,o=gm(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:o.ok,error_count:o.errorCount,warning_count:o.warningCount,findings:o.findings,warnings:t.warnings,generated_at:S()}}function Ch(e,t){return Ah.join(e,"templates",`${t}.json`)}async function Rh(e,t){let n=await de(Ch(e,t));if(n!==null)try{let o=JSON.parse(n);if(o!==null&&typeof o=="object"&&!Array.isArray(o)){let r=o.options;if(r!==null&&typeof r=="object"&&!Array.isArray(r))return r}}catch{}}async function Tm(e,t,n,o){let r=new Map;for(let i of o.templates){let s=await Rh(e,i.name);s!==void 0&&r.set(i.name,s)}return{typesRaw:await de(Pe(e,t.files.types,Fe.types)),statusesRaw:await de(Pe(e,t.files.statuses,Fe.statuses)),fieldsRaw:await de(Pe(e,t.files.fields,Fe.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:r,installedPackages:new Set}}function ut(e){let t=[],n=[],o=[];for(let r of e)(r.status==="add"?t:r.status==="update"?n:o).push(r.key);return{added:t,updated:n,unchanged:o}}function Om(e,t,n,o,r){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:o,changed:t.changed,types:ut(t.types.changes),statuses:ut(t.statuses.changes),fields:ut(t.fields.changes),workflows:ut(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:ut(t.config.changes),templates:ut(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(r)].sort((i,s)=>i.localeCompare(s)),generated_at:S()}}async function Th(e){await P(e)}function Oh(e){try{let t=io(e,co());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new p(t instanceof Error?t.message:String(t),u.USAGE)}}async function Mm(e,t,n){let o=x(process.cwd(),n.path);await Th(o);let r=Oh(e),i=r.profile,s=r.warnings;for(let v of i.fields){let _;try{_=fe(v)}catch{continue}Ac(_)}let a=t.dryRun===!0,c=await I(o),l=hs(c.schema);if(a){let v=await Tm(o,l,c,i),_=$m(i,v);return Om(i,_,!1,!0,[...s])}let d=C(t.author,c.author_default),m=ca(c),f=!!t.force,g=[...s],y=[],k=async v=>{y.push(await Le(o,v,c.locks.ttl_seconds,d,f,m.force_required_for_stale_lock,c.locks.wait_ms))},b;try{await k(xh),await k(Ih),await k(Eh);let v=await Tm(o,l,c,i);if(b=$m(i,v),b.types.changed){let _=Pe(o,l.files.types,Fe.types);await tt({pmRoot:o,filePath:_,raw:In(b.types.file),op:"profile:apply-types",author:d,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let A=new Set(i.types.map(O=>ue(O).name)),N=b.types.file.definitions.filter(O=>A.has(O.name));await il(o,N,g,"profile:apply-type-folder"),g.push(...await G({path:_,scope:"project",op:"profile:apply-types"}))}if(b.statuses.changed){let _=Pe(o,l.files.statuses,Fe.statuses);await tt({pmRoot:o,filePath:_,raw:qn(b.statuses.file),op:"profile:apply-statuses",author:d,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),g.push(...await G({path:_,scope:"project",op:"profile:apply-statuses"}))}if(b.fields.changed){let _=Pe(o,l.files.fields,Fe.fields);await tt({pmRoot:o,filePath:_,raw:Nn(b.fields.file),op:"profile:apply-fields",author:d,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),g.push(...await G({path:_,scope:"project",op:"profile:apply-fields"}))}if(b.config.changed||b.workflows.changed){for(let _ of b.config.changes){if(_.status==="unchanged")continue;let A=ct(_.key);A!==void 0&&vl(c,A,_.value)}c.schema.type_workflows=b.workflows.result,await la(o,c,"profile:apply-config")}for(let _ of b.templates.changes)_.status!=="unchanged"&&await _i(_.name,{..._.options},n)}finally{for(let v of y.reverse())try{await v()}catch{}}return Om(i,b,b.changed,!1,g)}function $m(e,t){try{return wm(e,t)}catch(n){throw new p(n instanceof Error?n.message:String(n),u.USAGE)}}function $h(e,t){let n=[];if(t.added.length>0&&n.push(`+${t.added.join(", ")}`),t.updated.length>0&&n.push(`~${t.updated.join(", ")}`),n.length!==0)return` ${e}: ${n.join(" ")}`}function gS(e){let t=["Project profiles:"];for(let n of e.profiles){let o=n.source==="extension"?` [${n.package??"extension"}]`:"";t.push(` ${n.name} \u2014 ${n.title}: ${n.summary}${o}`)}for(let n of e.warnings)t.push(` warning: ${n}`);return t.join(`
61
- `)}function yS(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=[`${e.name} \u2014 ${e.title}${t}`,e.summary,""];n.push(`types: ${e.types.join(", ")||"(none)"}`),n.push(`statuses: ${e.statuses.join(", ")||"(none)"}`),n.push(`fields: ${e.fields.join(", ")||"(none)"}`),n.push(`workflows: ${e.workflows.join(", ")||"(none)"}`),n.push(`config: ${e.config.join(", ")||"(none)"}`),n.push(`templates: ${e.templates.join(", ")||"(none)"}`),n.push(`packages: ${e.packages.map(o=>o.spec).join(", ")||"(none)"}`);for(let o of e.warnings)n.push(`warning: ${o}`);return n.join(`
62
- `)}function bS(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=e.warning_count+e.warnings.length,r=[e.ok?`Profile ${e.name}${t}: ok (${n} warning${n===1?"":"s"})`:`Profile ${e.name}${t}: ${e.error_count} error${e.error_count===1?"":"s"}, ${n} warning${n===1?"":"s"}`];for(let i of e.findings){let s=i.target!==void 0?` (${i.target})`:"";r.push(` ${i.severity} [${i.code}] ${i.dimension}${s}: ${i.message}`)}for(let i of e.warnings)r.push(` warning: ${i}`);return r.join(`
63
- `)}function wS(e){let t=e.dry_run?"dry-run":e.applied?"applied":"no changes",n=[`Profile ${e.name} (${t})`];if(!e.changed)n.push(" already up to date");else for(let[r,i]of[["types",e.types],["statuses",e.statuses],["fields",e.fields],["workflows",e.workflows],["config",e.config],["templates",e.templates]]){let s=$h(r,i);s!==void 0&&n.push(s)}let o=e.packages.filter(r=>r.status==="recommended");o.length>0&&n.push(` recommended packages: ${o.map(r=>r.spec).join(", ")}`);for(let r of e.warnings)n.push(` warning: ${r}`);return n.join(`
64
- `)}import{readFile as Fh,writeFile as Gm}from"node:fs/promises";import Ph from"node:path";var Dm=["item","history","relationship","json"];function Nh(e){let t=e.trim().toLowerCase();if(Dm.includes(t))return t;throw new p(`Unknown merge artifact "${e}". Supported values: ${Dm.join(", ")}.`,u.USAGE)}function Lh(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new p(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,u.USAGE)}async function hi(e,t){try{return await Fh(e,"utf8")}catch{throw new p(`Cannot read merge ${t} file at ${e}.`,u.NOT_FOUND)}}async function Mh(e){let t=x(process.cwd(),e.path);return await ke(Se(t))?I(t):null}function Dh(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function jm(e,t){try{return e()}catch(n){if(n instanceof p&&n.context?.code==="item_identity_conflict"){let o=r=>r.endsWith(`
59
+ `}},Vk={normalizeTemplateName:so,extractTemplateOptions:Em,parseStoredTemplateDocument:fi,builtinTemplateDocument:Cm,readStoredTemplateDocument:Tm};function so(e){let t=e.trim();if(!xm.test(t))throw new p(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,u.USAGE);return t}function mi(e){return Am.join(e,yh)}function ao(e,t){return Am.join(mi(e),`${t}${di}`)}async function pi(e){await P(e)}function ui(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Em(e){let t={};for(let[n,o]of Object.entries(e))if(o!==void 0){if(n==="priority"){t[n]=String(In(o));continue}if(wh.has(n)){if(typeof o=="string"){t[n]=[o];continue}if(!Array.isArray(o))continue;let r=o.filter(i=>typeof i=="string");r.length>0&&(t[n]=r);continue}if(typeof o=="string"){t[n]=o;continue}Array.isArray(o)&&o.every(r=>typeof r=="string")&&(t[n]=[...o])}return ui(t)}function vh(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(`Template "${t}" has invalid options payload.`,u.GENERIC_FAILURE);let n=e,o={};for(let[r,i]of Object.entries(n)){let s=r.trim();if(s.length===0)throw new p(`Template "${t}" contains an empty option key.`,u.GENERIC_FAILURE);if(typeof i=="string"){o[s]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){o[s]=[...i];continue}throw new p(`Template "${t}" contains invalid value for option "${s}".`,u.GENERIC_FAILURE)}return ui(o)}function fi(e,t){let n;try{n=JSON.parse(e)}catch{throw new p(`Template "${t}" contains invalid JSON.`,u.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Template "${t}" has invalid document shape.`,u.GENERIC_FAILURE);let o=n,r=vh(o.options,t),i=S();return{name:typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():t,created_at:typeof o.created_at=="string"?o.created_at:i,updated_at:typeof o.updated_at=="string"?o.updated_at:i,options:r}}function Cm(e){let t=Im[e];return t?{name:e,created_at:km,updated_at:km,options:ui({...t})}:null}async function Rm(e,t){let n=await de(ao(e,t));if(n!==null)return{document:fi(n,t),source:"user"};let o=Cm(t);if(o)return{document:o,source:"builtin"};throw new p(`Template "${t}" not found`,u.NOT_FOUND)}async function Tm(e,t){let n=await de(ao(e,t));if(n===null)throw new p(`Template "${t}" not found`,u.NOT_FOUND);return fi(n,t)}async function kh(e,t){let n=so(t),{document:o}=await Rm(e,n);return o.options}async function _i(e,t,n){let o=x(process.cwd(),n.path);await pi(o);let r=so(e),i=Em(t);if(Object.keys(i).length===0)throw new p("templates save requires at least one create option flag",u.USAGE);let s=S(),a=ao(o,r),c=s;await ke(a)&&(c=(await Tm(o,r)).created_at);let l={name:r,created_at:c,updated_at:s,options:i},d=await I(o);return await Sm.mkdir(mi(o),{recursive:!0}),await tt({pmRoot:o,filePath:a,raw:`${JSON.stringify(l,null,2)}
60
+ `,op:"templates:save",author:C(void 0,d.author_default),lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms}),{name:l.name,created_at:l.created_at,updated_at:l.updated_at,path:a,options:l.options}}async function Sh(e){let t=mi(e);return await ke(t)?(await Sm.readdir(t)).filter(o=>o.toLowerCase().endsWith(di)).map(o=>o.slice(0,-di.length)).filter(o=>xm.test(o)):[]}async function Ah(e){let t=x(process.cwd(),e.path);await pi(t);let n=await Sh(t),o=new Set(n),r=Object.keys(Im).filter(c=>!o.has(c)),i=[...n].sort((c,l)=>c.localeCompare(l)),s=[...r].sort((c,l)=>c.localeCompare(l)),a=[...new Set([...i,...s])].sort((c,l)=>c.localeCompare(l));return{templates:a,count:a.length,builtin_templates:s,user_templates:i}}async function xh(e,t){let n=x(process.cwd(),t.path);await pi(n);let o=so(e),{document:r,source:i}=await Rm(n,o);return{name:r.name,source:i,created_at:r.created_at,updated_at:r.updated_at,path:i==="builtin"?`builtin:${o}`:ao(n,o),options:r.options}}var Pm=["list","show","apply","lint"],Eh="schema-types",Ch="schema-statuses",Rh="schema-fields";function co(){let e=T();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Nm(){let{profiles:e,warnings:t}=si(co());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:ci(n.definition)})),warnings:t,generated_at:S()}}function Lm(e){let t;try{t=io(e,co())}catch(o){throw new p(o instanceof Error?o.message:String(o),u.USAGE)}let{resolved:n}=t;return{action:"show",...hm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Mm(e){let t;try{t=io(e,co())}catch(r){throw new p(r instanceof Error?r.message:String(r),u.USAGE)}let{resolved:n}=t,o=ym(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:o.ok,error_count:o.errorCount,warning_count:o.warningCount,findings:o.findings,warnings:t.warnings,generated_at:S()}}function Th(e,t){return Ih.join(e,"templates",`${t}.json`)}async function Oh(e,t){let n=await de(Th(e,t));if(n!==null)try{let o=JSON.parse(n);if(o!==null&&typeof o=="object"&&!Array.isArray(o)){let r=o.options;if(r!==null&&typeof r=="object"&&!Array.isArray(r))return r}}catch{}}async function Om(e,t,n,o){let r=new Map;for(let i of o.templates){let s=await Oh(e,i.name);s!==void 0&&r.set(i.name,s)}return{typesRaw:await de(Pe(e,t.files.types,Fe.types)),statusesRaw:await de(Pe(e,t.files.statuses,Fe.statuses)),fieldsRaw:await de(Pe(e,t.files.fields,Fe.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:r,installedPackages:new Set}}function ut(e){let t=[],n=[],o=[];for(let r of e)(r.status==="add"?t:r.status==="update"?n:o).push(r.key);return{added:t,updated:n,unchanged:o}}function $m(e,t,n,o,r){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:o,changed:t.changed,types:ut(t.types.changes),statuses:ut(t.statuses.changes),fields:ut(t.fields.changes),workflows:ut(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:ut(t.config.changes),templates:ut(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(r)].sort((i,s)=>i.localeCompare(s)),generated_at:S()}}async function $h(e){await P(e)}function Fh(e){try{let t=io(e,co());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new p(t instanceof Error?t.message:String(t),u.USAGE)}}async function Dm(e,t,n){let o=x(process.cwd(),n.path);await $h(o);let r=Fh(e),i=r.profile,s=r.warnings;for(let v of i.fields){let _;try{_=pe(v)}catch{continue}Ac(_,v)}let a=t.dryRun===!0,c=await I(o),l=ys(c.schema);if(a){let v=await Om(o,l,c,i),_=Fm(i,v);return $m(i,_,!1,!0,[...s])}let d=C(t.author,c.author_default),m=da(c),f=!!t.force,g=[...s],y=[],k=async v=>{y.push(await Le(o,v,c.locks.ttl_seconds,d,f,m.force_required_for_stale_lock,c.locks.wait_ms))},b;try{await k(Eh),await k(Ch),await k(Rh);let v=await Om(o,l,c,i);if(b=Fm(i,v),b.types.changed){let _=Pe(o,l.files.types,Fe.types);await tt({pmRoot:o,filePath:_,raw:En(b.types.file),op:"profile:apply-types",author:d,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let A=new Set(i.types.map(O=>fe(O).name)),N=b.types.file.definitions.filter(O=>A.has(O.name));await il(o,N,g,"profile:apply-type-folder"),g.push(...await G({path:_,scope:"project",op:"profile:apply-types"}))}if(b.statuses.changed){let _=Pe(o,l.files.statuses,Fe.statuses);await tt({pmRoot:o,filePath:_,raw:qn(b.statuses.file),op:"profile:apply-statuses",author:d,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),g.push(...await G({path:_,scope:"project",op:"profile:apply-statuses"}))}if(b.fields.changed){let _=Pe(o,l.files.fields,Fe.fields);await tt({pmRoot:o,filePath:_,raw:bn(b.fields.file),op:"profile:apply-fields",author:d,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),g.push(...await G({path:_,scope:"project",op:"profile:apply-fields"}))}if(b.config.changed||b.workflows.changed){for(let _ of b.config.changes){if(_.status==="unchanged")continue;let A=ct(_.key);A!==void 0&&vl(c,A,_.value)}c.schema.type_workflows=b.workflows.result,await ma(o,c,"profile:apply-config")}for(let _ of b.templates.changes)_.status!=="unchanged"&&await _i(_.name,{..._.options},n)}finally{for(let v of y.reverse())try{await v()}catch{}}return $m(i,b,b.changed,!1,g)}function Fm(e,t){try{return vm(e,t)}catch(n){throw new p(n instanceof Error?n.message:String(n),u.USAGE)}}function Ph(e,t){let n=[];if(t.added.length>0&&n.push(`+${t.added.join(", ")}`),t.updated.length>0&&n.push(`~${t.updated.join(", ")}`),n.length!==0)return` ${e}: ${n.join(" ")}`}function bS(e){let t=["Project profiles:"];for(let n of e.profiles){let o=n.source==="extension"?` [${n.package??"extension"}]`:"";t.push(` ${n.name} \u2014 ${n.title}: ${n.summary}${o}`)}for(let n of e.warnings)t.push(` warning: ${n}`);return t.join(`
61
+ `)}function wS(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=[`${e.name} \u2014 ${e.title}${t}`,e.summary,""];n.push(`types: ${e.types.join(", ")||"(none)"}`),n.push(`statuses: ${e.statuses.join(", ")||"(none)"}`),n.push(`fields: ${e.fields.join(", ")||"(none)"}`),n.push(`workflows: ${e.workflows.join(", ")||"(none)"}`),n.push(`config: ${e.config.join(", ")||"(none)"}`),n.push(`templates: ${e.templates.join(", ")||"(none)"}`),n.push(`packages: ${e.packages.map(o=>o.spec).join(", ")||"(none)"}`);for(let o of e.warnings)n.push(`warning: ${o}`);return n.join(`
62
+ `)}function vS(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=e.warning_count+e.warnings.length,r=[e.ok?`Profile ${e.name}${t}: ok (${n} warning${n===1?"":"s"})`:`Profile ${e.name}${t}: ${e.error_count} error${e.error_count===1?"":"s"}, ${n} warning${n===1?"":"s"}`];for(let i of e.findings){let s=i.target!==void 0?` (${i.target})`:"";r.push(` ${i.severity} [${i.code}] ${i.dimension}${s}: ${i.message}`)}for(let i of e.warnings)r.push(` warning: ${i}`);return r.join(`
63
+ `)}function kS(e){let t=e.dry_run?"dry-run":e.applied?"applied":"no changes",n=[`Profile ${e.name} (${t})`];if(!e.changed)n.push(" already up to date");else for(let[r,i]of[["types",e.types],["statuses",e.statuses],["fields",e.fields],["workflows",e.workflows],["config",e.config],["templates",e.templates]]){let s=Ph(r,i);s!==void 0&&n.push(s)}let o=e.packages.filter(r=>r.status==="recommended");o.length>0&&n.push(` recommended packages: ${o.map(r=>r.spec).join(", ")}`);for(let r of e.warnings)n.push(` warning: ${r}`);return n.join(`
64
+ `)}import{readFile as Nh,writeFile as Um}from"node:fs/promises";import Lh from"node:path";var jm=["item","history","relationship","json"];function Mh(e){let t=e.trim().toLowerCase();if(jm.includes(t))return t;throw new p(`Unknown merge artifact "${e}". Supported values: ${jm.join(", ")}.`,u.USAGE)}function Dh(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new p(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,u.USAGE)}async function hi(e,t){try{return await Nh(e,"utf8")}catch{throw new p(`Cannot read merge ${t} file at ${e}.`,u.NOT_FOUND)}}async function jh(e){let t=x(process.cwd(),e.path);return await ke(Se(t))?I(t):null}function Gh(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Gm(e,t){try{return e()}catch(n){if(n instanceof p&&n.context?.code==="item_identity_conflict"){let o=r=>r.endsWith(`
65
65
  `)?r:`${r}
66
- `;throw await Gm(t.outputPath,`<<<<<<< pm ours
66
+ `;throw await Um(t.outputPath,`<<<<<<< pm ours
67
67
  ${o(t.oursRaw)}||||||| pm base
68
68
  ${o(t.baseRaw)}=======
69
69
  ${o(t.theirsRaw)}>>>>>>> pm theirs
70
- `,"utf8"),new p(`Unresolved identity for ${t.itemPath}: both snapshots remain in conflict markers. ${n.message}`,n.exitCode,{...n.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw n}}async function Um(e,t){let n=Nh(e.artifact),o=Lh(e.prefer),r=Ph.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([hi(e.basePath,"base"),hi(e.oursPath,"ours"),hi(e.theirsPath,"theirs")]),c,l,d=[],m={},f={baseRaw:i,oursRaw:s,theirsRaw:a,outputPath:r,itemPath:e.itemPath??r};if(n==="history"){let y=await jm(()=>Tl(i,s,a),f);c=y.merged,m.history={strategy:y.strategy,common_entries:y.common_entries,entries_from_ours:y.entries_from_ours,entries_from_theirs:y.entries_from_theirs,entries_total:y.entries_total,reanchored:y.reanchored}}else if(n==="relationship"){let y=Ol(i,s,a);c=y.merged,m.relationship={strategy:y.strategy,common_entries:y.common_entries,entries_from_ours:y.entries_from_ours,entries_from_theirs:y.entries_from_theirs,entries_total:y.entries_total,reanchored:y.reanchored}}else if(n==="item"){let y=await Mh(t),k=Dh(e.itemPath??r,y),b=pe(T()),v=await jm(()=>$l(i,s,a,{format:k,schema:y?.schema,extensionFieldNames:b,preferred:o,conflictResolution:"latest_document_update"}),f);if(c=v.merged,d.push(...v.conflict_fields),m.item={fields_from_theirs:v.fields_from_theirs,union_fields:v.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let _=bn(c,{format:k,schema:y?.schema,extensionFieldNames:b}),A=_.metadata,N=[...new Set([...v.fields_from_theirs,...v.union_fields,...v.conflict_decisions.map(O=>O.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:o,conflictResolution:"latest_document_update",fieldsFromTheirs:v.fields_from_theirs,unionFields:v.union_fields,mergedFieldHashes:Object.fromEntries(N.map(O=>[O,Rl(O==="body"?_.body:A[O])])),decisions:v.conflict_decisions,operation:await Pl(process.cwd(),e.itemPath,s)}}}else{let y=Fl(i,s,a,{preferred:o});c=y.merged,d.push(...y.conflict_paths),m.json={paths_from_theirs:y.paths_from_theirs}}if(await Gm(r,c,"utf8"),l!==void 0){let y=await Ll(l);y!==null&&(m.receipt=Ue(y))}let g=[];if(d.length>0){let y=m.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${m.receipt.receipt_id} with item ${m.receipt.item_id}; clone-local discarded values are never copied into this result.`;g.push(`Both branches changed ${d.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${y} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&m.history?.reanchored&&g.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:d.length===0,artifact:n,output_path:r,requested_preference:o,conflicts:d,...m,guidance:g,generated_at:S()}}async function qm(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Nl(e.cwd,n.item_path,n.operation))continue;let o={gitWorkspaceRoot:e.cwd,receipt:n};await Ee(n.item_id,{dryRun:!0,mergeAbandonmentProof:o},e.global),e.dryRun||(await Ee(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:o,message:e.message??`Settle ${n.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...Ue(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Bn(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as jh}from"node:fs/promises";import Gh from"node:path";var Uh=4;function zm(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,o=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,r=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,s=Array.isArray(r)?r.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:o,truncated:i,coordinates:s}}async function qh(e,t){let n=[];for(let o of t){let r;try{r=await jh(Gh.join(e,"history",`${o.item_id}.jsonl`),"utf8")}catch{continue}let i=r.split(/\r?\n/)[o.history_line-1];if(i===void 0||i.trim().length===0)continue;let s;try{s=JSON.parse(i)}catch{continue}let a=ql(s,o.item_id).find(c=>c.receiptId===o.receipt_id);a===void 0||!Ul(a)||a.eventTimestamp===void 0||ps(a.eventTimestamp,Gl)>=0||n.push({...o,original_event_ts:a.eventTimestamp})}return n}async function zh(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let o=t.get(n.item_id)??[];o.push(n),t.set(n.item_id,o)}for(let[n,o]of t)await Ee(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:o.map(r=>({receipt_id:r.receipt_id,original_history_line:r.history_line,original_event_ts:r.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function Hh(e){try{return{status:"fulfilled",value:await Ee(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function Bh(e){e.results.forEach((t,n)=>{let o=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let r=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:o,outcome:r,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[r]+=1;return}e.repair.streams.push({id:o,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function Wh(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(o=>o.merge_receipt_proof?.trusted?o.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(o=>t.has(o.id));return await Promise.all(n.map(o=>Bn(e.receiptWorkspaceRoot,o,{requireExisting:!0}))),n.length}function Vh(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function Kh(e,t){if(e.force===!0)throw new p("Automatic staging cannot accept forced reconciliation.",u.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let n={...e,stage:!1},{stageLosslessMergeReconciliation:o,resolveMergeSettlementGlobal:r}=await import("./stage-N5GDBS5A.js"),i=await r(t),s=await lo({...n,dryRun:!0},i);return o({preview:s,dryRun:e.dryRun===!0,global:i,apply:()=>lo({...n,dryRun:!1},i)})}async function lo(e,t){return e.stage===!0?Kh(e,t):Jh(e,t)}async function Jh(e,t){let n=e.dryRun===!0,o=x(process.cwd(),t.path),r=await Vt(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=zm(r),s=await qh(o,i.coordinates),a=await Yc(o),c=a??o,l=await Ml(c,{includeLossless:!0,pmRoot:o});if(l.invalid_evidence_count>0)throw new p(`Merge reconciliation refused ${l.invalid_evidence_count} invalid receipt evidence file(s).`,u.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});Dl(l.receipts.map(L=>L.id),l,n);let d=await zh({candidates:s,options:e,global:t}),m=l.receipts,f=await qm({cwd:a,receipts:m,dryRun:n,author:e.author,message:e.message,global:t}),g=new Set(f),y=new Map;for(let L of m.filter(ve=>!g.has(ve.id))){let ve=y.get(L.item_id)??[];ve.push(L),y.set(L.item_id,ve)}let k=Object.fromEntries([...y].map(([L,ve])=>[L,{merge:{receipts:ve.map(Ue)}}])),b=Object.fromEntries([...y].map(([L,ve])=>[L,{gitWorkspaceRoot:a,receipts:ve}])),v=await Wn({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:k,...m.length>0?{mergeReceiptProofById:b}:{}},t),_=new Set(v.streams.map(L=>L.id)),A=[...y.keys()].filter(L=>!_.has(L)),N=await $a(A,Uh,L=>Hh({id:L,dryRun:n,options:e,global:t,auditContext:k[L],mergeReceiptProof:b[L]}));Bh({receiptOnlyIds:A,results:N,repair:v});let O=await Wh({dryRun:n,pendingReceipts:m,repair:v,receiptWorkspaceRoot:c}),B=await Vn({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),$=d===0?r:await Vt(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),R=zm($),ie=B.checks.every(L=>L.status==="ok"),Tt=n?m.length===0:O+f.length===m.length,ne=[v.totals.failed===0,ie,Tt,R.count===0,!R.truncated].every(Boolean),Ve=i.truncated||R.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,Ke=Vh(m.length,ne),ku=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",Ve,Ke,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:ne?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",Ve,Ke,...s.length>0&&d===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(L=>L!==void 0);return{ok:ne,dry_run:n,repair:v,receipts:{pending_before:m.length,reconciled:O,abandoned:f.length,summaries:m.map(Ue),unstaged_durable_receipt_ids:l.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:d,missing_history_references_after:R.count},validation:B,guidance:ku,generated_at:B.generated_at}}var Yh="1h",Xh="now",Zh="+1d";function Te(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Hm(e,t,n){let o={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,inheritFocus:n.inheritFocus,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return le(n,o)}async function Bm(e,t,n,o){let r=Hm(e,t,n),i=[];return Te(i,"start",n.start??Xh),n.end!==void 0?Te(i,"end",n.end):Te(i,"duration",n.duration??Yh),Te(i,"location",n.location),Te(i,"timezone",n.timezone),n.allDay===!0&&Te(i,"all_day","true"),r.event=[i.join(",")],Ce(r,o)}function Wm(e,t,n){return Bm("Meeting",e,t,n)}function Vm(e,t,n){return Bm("Event",e,t,n)}function Km(e,t,n){let o=Hm("Reminder",e,t),r=[];return Te(r,"at",t.at??Zh),Te(r,"text",t.text??e),o.reminder=[r.join(",")],Ce(o,n)}function en(e){let t={...e.args,...e.options};return le(e.options,t)}function ye(e,t){let n=h(e,t);if(n!==void 0)return n;throw new p(`Missing required parameter: ${t}`,u.USAGE)}function ft(e){return typeof e=="string"?[e]:U(e)}function Jm(e){return ld(en(e),e.global)}function Ym(e){let t=en(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new p("Mutation event cursor mode must be batch or row.",u.USAGE,{code:"invalid_event_cursor_mode"});let o=n;return dd({cwd:h(t,"cwd"),pmRoot:h(t,"path"),since:h(t,"since"),type:ft(t.type),author:ft(t.author),item:ft(t.item),limit:t.limit===void 0?void 0:Y(t.limit,"limit"),full:t.full===!0,...t.verify===!0?{verify:!0}:{},...o===void 0?{}:{cursorMode:o},...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:ft(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:ft(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:ft(t.provenanceFilter)}})}function Xm(e){let t=en(e),n=ye(t,"subcommand");if(n==="install")return Xc({dryRun:t.dryRun===!0,preCommitHook:t.preCommitHook===!0},e.global);if(n==="reconcile")return lo({dryRun:t.dryRun===!0,author:h(t,"author"),message:h(t,"message"),force:t.force===!0,stage:t.stage===!0},e.global);if(n==="report")return jl({includeReconciled:t.includeReconciled===!0,cwd:h(t,"cwd")});if(n==="driver")return Um({artifact:ye(t,"artifact"),basePath:ye(t,"basePath"),oursPath:ye(t,"oursPath"),theirsPath:ye(t,"theirsPath"),outputPath:h(t,"outputPath")??h(t,"output"),itemPath:h(t,"itemPath"),prefer:h(t,"prefer")},e.global);throw ae({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Zm(e){let t=en(e),n=ye(t,"subcommand");if(n==="position")return gd(e.global);if(n!=="snapshot")throw ae({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let o=h(t,"snapshotAction")??ye(t,"snapshot_action"),r=x(process.cwd(),e.global.path);if(o==="create")return md(r,{name:h(t,"name")});if(o==="list")return ud(r);let i=ye(t,"target");if(o==="inspect")return pd(r,i);if(o==="delete")return hd(r,i);if(o==="restore")return t.dryRun===!0?fd(r,i):_d(r,i,{force:t.force===!0,author:h(t,"author"),message:h(t,"message"),lockTtlSeconds:Y(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Y(t.lockWaitMs,"lockWaitMs")});throw ae({command_path:"workspace snapshot",token:o,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function mo(e){let t=en(e),n=ye(t,"title");return e.action==="meet"?Wm(n,t,e.global):e.action==="event"?Vm(n,t,e.global):Km(n,t,e.global)}function Qm(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:h(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:U(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:h(e,"measurementSource"),measurementItem:h(e,"measurementItem"),measurementRevision:h(e,"measurementRevision"),author:h(e,"author"),message:h(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:h(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}function ep(e,t,n){let o;if(typeof e.lines=="string")o=dr(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");o=dr(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:o,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}function K(e,t){let n=h(e,t);if(!n)throw new p(`Missing required argument: ${t}`,64);return n}function be(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Qh(e){let t=h(e.args,"subcommand")??K(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:h(e.args,"name")??h(e.options,"name"),author:h(e.args,"author")??h(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:U(n)}}function eg(e){let{ctx:t,subcommand:n,name:o,author:r,force:i}=e,a=be({list:()=>cl(t.global),show:()=>ll(o,t.global),"show-status":()=>dl(o,t.global),"list-fields":()=>ul(t.global),"show-field":()=>fl(o,t.global),"remove-type":()=>rl(o,{author:r,force:i},t.global),"remove-field":()=>pl(o,{author:r,force:i},t.global),"remove-status":()=>al(o,{author:r,force:i},t.global),"apply-preset":()=>_l(h(t.args,"typePreset")??h(t.options,"typePreset"),{author:r,force:i},t.global)},n);return a?a():null}function tg(e){let{ctx:t,name:n,author:o,force:r,aliases:i}=e,s=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return ml(n,{type:h(t.args,"fieldType")??h(t.options,"fieldType"),commands:s===void 0?void 0:U(s),description:h(t.args,"description")??h(t.options,"description"),cliFlag:h(t.args,"cliFlag")??h(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:U(a),author:o,force:r},t.global)}function ng(e){let{ctx:t,name:n,author:o,force:r,aliases:i}=e,s=t.args.role??t.options.role;return sl(n,{role:s===void 0?void 0:U(s),alias:i,description:h(t.args,"description")??h(t.options,"description"),order:Y(t.args.order??t.options.order,"schema add-status order"),author:o,force:r},t.global)}function og(e){let{ctx:t,name:n,author:o,force:r,aliases:i}=e;return ol(n,{description:h(t.args,"description")??h(t.options,"description"),defaultStatus:h(t.args,"defaultStatus")??h(t.args,"default_status")??h(t.options,"defaultStatus")??h(t.options,"default_status"),folder:h(t.args,"folder")??h(t.options,"folder"),alias:i,author:o,force:r},t.global)}function rg(e){let{ctx:t,subcommand:n,name:o,author:r,force:i}=e,s=h(t.args,"to")??K(t.options,"to"),a=h(t.args,"migrationId")??h(t.args,"migration_id")??h(t.options,"migrationId")??h(t.options,"migration_id"),c=h(t.args,"fieldTypeScope")??h(t.options,"fieldTypeScope")??h(t.args,"type")??h(t.options,"type"),l=n==="rename-type"?{kind:"rename-type",from:o??"",to:s}:n==="rename-field"?{kind:"rename-field",from:o??"",to:s,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:o??"",to:s};return tl(l,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:r,force:i},t.global)}function tp(e){let t=Qh(e);Xi(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=dn.find(r=>r===t.subcommand);if(n)return el(n,t.name,{definition:e.args.definition??e.options.definition,policy:h(e.args,"policy")??h(e.options,"policy"),message:h(e.args,"message")??h(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let o=eg(t);if(o!==null)return o;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return rg(t);if(t.subcommand==="add-field")return tg(t);if(t.subcommand==="add-status")return ng(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?hl({minCount:Y(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):og(t);throw ae({command_path:"schema",token:t.subcommand,allowed:nl,exit_code:64})}function po(e){return h(e.args,"target")??h(e.options,"target")}function q(e,t=e.options){return e.id??K(t,"id")}async function ig(e){let t=Qe("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Nr(await _e(h(e.args,"status")??h(t,"status"),t,e.global),t)}async function sg(e){let t=h(e.args,"query")??h(e.args,"keywords")??K(e.args,"query"),n=Qe("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Nr(await Ar(t,n,e.global),n)}async function ag(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await Ce(o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function cg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r={...o,...o.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...o.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return H(await Dr(q(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function lg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await lt(q(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function dg(e){let t=Me(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0),Pd(q(e),t,e.global)}function np(e,t){return El(ep(e.options,t,Y),e.global)}function mg(e){let t=U(e.options.lookupPath);if(t&&t.length>0)return np(e,t);let n=q(e);return e.options.discover===!0?mr(n,Mn(e.options),e.global):Il(n,Wt(Me(e.options)),e.global)}function pg(e){return yd({subcommand:h(e.args,"subcommand")??h(e.options,"subcommand"),limit:Lc(e.args,e.options)},e.global)}function ug(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Vt(e.global,t)}function fg(e){let t=h(e.args,"configAction")??h(e.options,"configAction")??h(e.options,"action");if(t===void 0)throw new p("Missing required argument: configAction",64);let n=h(e.args,"value")??h(e.options,"value"),o=h(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options,r=h(e.args,"key")??h(e.options,"key");return kl(h(e.args,"scope")??h(e.options,"scope")??Ys(r),t,r,o,e.global,h(e.options,"policy")===void 0?n:void 0)}function _g(e){let t=e.options;return od(nd(t),e.global)}function hg(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new p(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new p(`${t} must be a finite integer.`,64);let o=Number.parseInt(n,10);if(!Number.isInteger(o))throw new p(`${t} must be a finite integer.`,64);return o}}async function gg(e){let t=h(e.args,"subcommand")??K(e.options,"subcommand"),n=e.options,{changedFields:o,idOnly:r}=j(e.args,e.options),i=await sm({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:yg(e),reorderTo:hg(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&rr(e.args)&&(i.mutation_receipt=oo(i,void 0)),t==="show"?i:H(i,{changedFields:o,idOnly:r,compactEnvelope:o==="compact"&&!r})}function yg(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function bg(e){let t=h(e.args,"subcommand")??K(e.options,"subcommand"),n=t.trim().toLowerCase(),o=h(e.args,"name")??h(e.options,"name"),i=be({list:()=>Pm(),show:()=>Nm(o),lint:()=>Lm(o),apply:()=>Mm(o,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:h(e.args,"author")??h(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!i)throw ae({command_path:"profile",token:t,allowed:Fm,exit_code:64});return i()}async function wg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await jd(q(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function vg(e){let{changedFields:t,runnerOptions:n}=j(e.args,e.options);return H(await mm(jn(n,!rr(e.args)),e.global),{changedFields:t})}async function kg(e){let{changedFields:t,runnerOptions:n}=j(e.args,e.options),o=h(e.args,"reason"),r=o!==void 0&&n.reason===void 0?{...n,reason:o}:{...n};return e.force&&r.force===void 0&&(r.force=!0),H(await zd(Dn(r),e.global),{changedFields:t})}async function Sg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r=h(o,"target")??K(e.args,"target");return H(await vr(q(e,o),r,o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Ag(e){let t={...e.args,...e.options};return Cl(K(t,"subcommand"),h(t,"id")??e.id,h(t,"target"),Uc(t),e.global)}function xg(e){return bl(x(process.cwd(),e.global.path),{...e.args,...e.options})}var gi={init:e=>yl(h(e.args,"prefix"),e.global,e.options),context:e=>hr(Qe("context",e.options),e.global),next:e=>gr(Qe("next",e.options),e.global),eval:Jm,events:Ym,merge:Xm,workspace:Zm,meet:mo,event:mo,remind:mo,list:ig,get:e=>{let t=q(e);return Sr(t,e.global,Qe("get",e.options,[t]))},search:sg,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:U(e.options.status);return lr(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:h(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Y(e.options.limit,"limit")})},create:ag,copy:cg,focus:e=>Gr(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:lg,"item-reopen":Kd,restore:Sg,claim:Bd,release:Vd,"start-task":e=>ze(e,"start_task"),"pause-task":e=>ze(e,"pause_task"),"close-task":e=>ze(e,"close_task"),close:Wd,comments:dg,notes:e=>um(q(e),Me(e.options),e.global),learnings:e=>Md(q(e),Me(e.options),e.global),files:mg,docs:e=>Al(q(e),Wt(Me(e.options)),e.global),test:e=>bd(q(e),Me(e.options),e.global),"test-all":e=>wd(e.options,e.global),telemetry:pg,validate:e=>Vn(e.options,e.global,{runUpdate:(t,n,o)=>lt(t,n,o)}),health:ug,assurance:e=>Hl(e.args,e.options,e.global),contracts:e=>Gn(e.options,e.global),config:fg,activity:_g,aggregate:e=>kr(e.options,e.global),extension:e=>zn(po(e),e.options,e.global),package:e=>zn(po(e),e.options,e.global),install:e=>zn(po(e),{...e.options,install:!0},e.global),upgrade:e=>Wl(po(e),e.options,e.global),delete:e=>jr(q(e),e.options,e.global),deps:e=>Sl(q(e),e.options,e.global),graph:Ag,"files-discover":e=>mr(q(e),e.options,e.global),"files-lookup":e=>np(e,U(e.options.paths)),history:e=>cd(q(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Yl(q(e),e.options,e.global),"history-repair":Nd,"history-compact":Ld,"history-attest":e=>Xl(e.options,e.global),"history-author-acknowledge":xg,plan:gg,schema:tp,profile:bg,stats:e=>xr(e.global,Qm(e.options)),append:wg,"update-many":vg,"close-many":kg,gc:e=>Bl(e.global,e.options)};var Oe=new Map;function yi(){Oe.clear()}function op(e,t){let n=Oe.get(e);if(n!==void 0)return n;if(Oe.size>=50){let r=Oe.keys().next().value;Oe.delete(r)}let o=t().catch(r=>{throw Oe.get(e)===o&&Oe.delete(e),r});return Oe.set(e,o),o}var Jx=Ui,Yx=qi,Xx=Bi,Zx=zi,Qx=Hi;function rp(e,t,n,o){let r=e.flag.slice(2).replace(/[-_]([a-z])/gu,(s,a)=>a.toUpperCase()),i=n.has(r);return{long:t,...o?{short:o}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:i?"string":"boolean",...i?{value_name:e.value_name??"value"}:{}}}function ip(e,t=[]){let n=new Set(t.flatMap(r=>r.keys)),o=[];for(let r of Ga(e.map(i=>({...i})))){o.push(rp(r,r.flag,n,r.short));for(let i of r.aliases??[])o.push(rp(r,i,n))}return o}var eI=ip(Fn,xc),Ig=ip(Pn,Ic);import cp from"node:path";function sp(e){return e.map(t=>({key:t.key,optionName:ys(t),metadataKey:t.metadata_key,type:t.type,commands:[...t.commands],repeatable:t.repeatable,requiredOnCreate:t.required_on_create,...t.description?{description:t.description}:{}}))}function ap(e){return e.map(t=>({command:t.command,action:t.action,arguments:t.arguments.map(n=>({name:n.name,required:n.required===!0,variadic:n.variadic===!0,description:n.description})),description:t.description,tier:t.tier??"standard",family:t.family??"extensions"}))}function Eg(e,t,n){return JSON.stringify([cp.resolve(e),cp.resolve(n??process.cwd()),t.extensions.enabled,t.extensions.disabled,t.extensions.policy])}async function Cg(e,t,n){let o=Eg(e,t,n);return op(o,()=>Tg(e,t,n))}async function Rg(e,t={}){let n=await I(e),o=t.extensionRegistrations??(t.noExtensions===!0?null:await Cg(e,n,t.cwd)),r=F(n,o),i=W(n.schema),s=Xe(n.schema);return{types:[...r.types],statuses:i.definitions.map(a=>a.id),openStatus:i.open_status,closeStatus:i.close_status,canceledStatus:i.canceled_status,fields:sp(s.definitions),extensionCommands:ap(o?.commands??[])}}async function Tg(e,t,n){let o=await vn({pmRoot:e,settings:t,cwd:n??process.cwd(),noExtensions:!1}),r=await Sn(o);try{return r.registrations}finally{try{await kn(o,r)}catch{}}}var Og=new Set(["true","1","yes","on"]),$g=new Set(["false","0","no","off"]);function Fg(e,t,n=[]){let o=[t,...n];for(let r of o){let i=e[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}}function Pg(e,t,n=[]){let o=[t,...n];for(let r of o){let i=e[r];if(i!==void 0){if(typeof i=="boolean")return i;if(typeof i=="string"){let s=i.trim().toLowerCase();if(Og.has(s))return!0;if($g.has(s))return!1}}}}function Ng(e,t,n=[]){for(let o of[t,...n]){let r=e[o],s=(typeof r=="string"?r.split(","):Array.isArray(r)?r.flatMap(a=>typeof a=="string"?a.split(","):[]):[]).map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}return[]}function z(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Lg(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t)&&t>=0)return t}}function Mg(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=4)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isInteger(t)&&t>=0&&t<=4)return t}return 2}function Dg(e){if(Array.isArray(e)){let t=e.filter(n=>typeof n=="string").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return Array.from(new Set(t)).sort((n,o)=>n.localeCompare(o))}return typeof e=="string"?$t(e):[]}function jg(e){let t=z(e);if(t){let n=Ne(t);if(n)return n}return"open"}function wi(e){if(typeof e=="number"&&Number.isInteger(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isInteger(t)?t:void 0}function lp(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e===1?!0:e===0?!1:void 0;if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:void 0}function _t(e){if(!Array.isArray(e))return;let t=e.map(n=>z(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}function bi(e){return pp(e,z)}function dp(e){return pp(e,fp)}function Gg(e,t){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=100)return e;let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;if(t.some(i=>i===o))return o;let r=Number(o);return Number.isInteger(r)&&r>=0&&r<=100?r:void 0}function mp(e,t){let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;return t.includes(o)?o:void 0}function vi(e){return z(e)?.toLowerCase()==="global"?"global":"project"}function Ug(e,t){let n=ki(e,t.allowScalar===!0);if(!n)return;let o=n.map(r=>Vg(r,t)).filter(r=>r!==void 0);return o.length>0?o:void 0}function qg(e,t={}){return up(e,t,(n,o)=>({path:n,scope:vi(o?.scope),note:z(o?.note)}))}function zg(e,t={}){return up(e,t,(n,o)=>({path:n,scope:vi(o?.scope),note:z(o?.note)}))}function Hg(e){let t=(Array.isArray(e)?e:[]).filter(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof o.field=="string"&&ws(o.field)!==void 0&&typeof o.reason=="string"&&o.reason.trim().length>0),n=new Map(t.map(o=>[o.field,{field:o.field,reason:o.reason}]));return ks([...n.values()])}function Bg(e,t={}){let n=ki(e,t.allowScalar===!0);if(!n)return;let o=n.map(r=>Yg(r,t)).filter(r=>r!==void 0);return o.length>0?o:void 0}function Wg(e,t){return C(e,t)}function fo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ki(e,t){return Array.isArray(e)?e:t?[e]:void 0}function uo(e,t){for(let n of t){let o=z(e[n]);if(o)return o}}function pp(e,t){if(!fo(e))return;let n=Object.entries(e).map(([o,r])=>[o.trim(),t(r)]).filter(o=>o[0].length>0&&o[1]!==void 0);return n.length>0?Object.fromEntries(n):void 0}function Vg(e,t){if(typeof e=="string")return Kg(e,t);if(!fo(e))return;let n=uo(e,t.textKeys??["text"]);if(!n)return;let o=t.createdAtKey??"created_at",r=t.authorKey??"author";return{created_at:(t.toIsoString?t.toIsoString(e[o]):z(e[o]))??t.fallbackCreatedAt,author:z(e[r])??t.fallbackAuthor,text:n}}function Kg(e,t){let n=z(e);return n?{created_at:t.fallbackCreatedAt,author:t.fallbackAuthor,text:n}:void 0}function up(e,t,n){let o=ki(e,t.allowScalar===!0);if(!o)return;let r=t.pathKeys??["path"],i=o.map(s=>Jg(s,r,n)).filter(s=>s!==void 0);return i.length>0?i:void 0}function Jg(e,t,n){if(typeof e=="string"){let r=z(e);return r?n(r):void 0}if(!fo(e))return;let o=uo(e,t);return o?n(o,e):void 0}function Yg(e,t){if(typeof e=="string"){let r=z(e);return r?{command:r,scope:"project"}:void 0}if(!fo(e))return;let n=uo(e,t.commandKeys??["command"]),o=uo(e,t.pathKeys??["path"]);if(!(!n&&(t.requireCommand===!0||!o)))return{...n?{command:n}:{},...o?{path:o}:{},scope:vi(e.scope),timeout_seconds:Xg(e.timeout_seconds,t),note:z(e.note),...typeof e.phase=="string"&&e.phase.trim().toLowerCase()==="setup"?{phase:"setup"}:{},...t.includeExtendedAssertions===!0?Zg(e):{}}}function Xg(e,t){let n=t.integerTimeout===!0?wi(e):fp(e);if(n===void 0)return;let o=t.timeoutMinimum??0;return t.timeoutExclusiveMinimum===!0?n>o?n:void 0:n>=o?n:void 0}function fp(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Zg(e){return{pm_context_mode:mp(e.pm_context_mode,["schema","tracker","auto"]),env_set:bi(e.env_set),env_clear:_t(e.env_clear),shared_host_safe:lp(e.shared_host_safe),assert_stdout_contains:_t(e.assert_stdout_contains),assert_stdout_regex:_t(e.assert_stdout_regex),assert_stderr_contains:_t(e.assert_stderr_contains),assert_stderr_regex:_t(e.assert_stderr_regex),assert_stdout_min_lines:wi(e.assert_stdout_min_lines),assert_json_field_equals:bi(e.assert_json_field_equals),assert_json_field_gte:dp(e.assert_json_field_gte)}}async function Qg(e){await P(e)}function _p(){return{metadata:{},body:""}}function ey(e){return[...Object.entries(e.metadata).filter(([,n])=>n!==void 0).map(([n])=>n),...e.body.length>0?["body"]:[]].sort()}async function ty(e){let{pmRoot:t,id:n,itemPath:o,author:r,message:i,settings:s,conflictWarningPrefix:a}=e,c={...e.document,metadata:{...e.document.metadata}};vs(c.metadata),pa(c.metadata,t);let l=Mt(c),d=me(t,n),m=_p(),f;try{f=await Dt(t,n,s.locks.ttl_seconds,r,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(g){if(g instanceof p&&g.exitCode===u.CONFLICT)return{committed:!1,conflictWarning:`${a}:${n}`};throw g}try{let g=F(s,T()).type_to_folder;if(await oe(t,n,s.id_prefix,s.item_format,g))return{committed:!1,conflictWarning:`${a}:${n}`};let y=await Cn({pmRoot:t,settings:s,operation:"import",author:r,before:null,after:l});return await An({pm_root:t,operation:"import",before:null,after:l,changed_fields:ey(l),author:r,sdk:Tn({pmRoot:t,settings:s,typeToFolder:g})}),await f.fence(async()=>{await se(o,Lt(l,{format:"toon"}));try{let b=jt({nowIso:S(),author:r,op:"import",before:m,after:l,message:i,context:y.decisions.length===0?void 0:{workflow_policies:y.decisions}});await Gt(d,b)}catch(b){throw await Ft(o),b}}),{committed:!0,writeWarnings:[...y.warnings,...await G({path:o,scope:"project",op:"import",item_id:l.metadata.id,item_type:l.metadata.type,before:m,after:l,changed_fields:["imported"]}),...await G({path:d,scope:"project",op:"import:history",item_id:l.metadata.id,item_type:l.metadata.type,before:m,after:l,changed_fields:["imported"]})]}}finally{await f.release()}}import{readFile as oy}from"node:fs/promises";import ry from"node:path";function ny(e){return e.trim().toLowerCase().replaceAll("_","-")}var Ai=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:Kc().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks (repository checkout only; excluded from the npm package).",optional:!0},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes (repository checkout only; excluded from the npm package).",optional:!0},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering (repository checkout only; not in the npm package).",optional:!0}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],Si=new Map;for(let e of Ai){Si.set(e.id,e);for(let t of e.aliases)Si.set(t,e)}function hp(){return Ai.map(e=>({...e,aliases:[...e.aliases],commands:[...e.commands],workflows:e.workflows.map(t=>({...t,commands:[...t.commands]})),docs:e.docs.map(t=>({...t})),related:[...e.related]}))}function _o(){return Ai.map(e=>e.id)}function gp(e){if(!e)return null;let t=ny(e);return t?Si.get(t)??null:null}var iy=["markdown","toon","json"],sy=["brief","standard","deep"];function ay(e){if(!e)return;let t=e.trim().toLowerCase();if(!iy.includes(t))throw new p("Guide format must be one of markdown|toon|json",u.USAGE);return t}function cy(e,t){let n=ay(e.format);if(t.json&&n&&n!=="json")throw new p("Cannot combine --json with --format markdown|toon",u.USAGE);return t.json?"json":n??"toon"}function ly(e){if(!e)return"brief";let t=e.trim().toLowerCase();if(!sy.includes(t))throw new p("Guide depth must be one of brief|standard|deep",u.USAGE);return t}function dy(){return Ms(process.env,"PM_CLI_PACKAGE_ROOT",import.meta.url,["..","..",".."])}function yp(e){return e.replaceAll(`\r
70
+ `,"utf8"),new p(`Unresolved identity for ${t.itemPath}: both snapshots remain in conflict markers. ${n.message}`,n.exitCode,{...n.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw n}}async function qm(e,t){let n=Mh(e.artifact),o=Dh(e.prefer),r=Lh.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([hi(e.basePath,"base"),hi(e.oursPath,"ours"),hi(e.theirsPath,"theirs")]),c,l,d=[],m={},f={baseRaw:i,oursRaw:s,theirsRaw:a,outputPath:r,itemPath:e.itemPath??r};if(n==="history"){let y=await Gm(()=>Tl(i,s,a),f);c=y.merged,m.history={strategy:y.strategy,common_entries:y.common_entries,entries_from_ours:y.entries_from_ours,entries_from_theirs:y.entries_from_theirs,entries_total:y.entries_total,reanchored:y.reanchored}}else if(n==="relationship"){let y=Ol(i,s,a);c=y.merged,m.relationship={strategy:y.strategy,common_entries:y.common_entries,entries_from_ours:y.entries_from_ours,entries_from_theirs:y.entries_from_theirs,entries_total:y.entries_total,reanchored:y.reanchored}}else if(n==="item"){let y=await jh(t),k=Gh(e.itemPath??r,y),b=ue(T()),v=await Gm(()=>$l(i,s,a,{format:k,schema:y?.schema,extensionFieldNames:b,preferred:o,conflictResolution:"latest_document_update"}),f);if(c=v.merged,d.push(...v.conflict_fields),m.item={fields_from_theirs:v.fields_from_theirs,union_fields:v.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let _=wn(c,{format:k,schema:y?.schema,extensionFieldNames:b}),A=_.metadata,N=[...new Set([...v.fields_from_theirs,...v.union_fields,...v.conflict_decisions.map(O=>O.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:o,conflictResolution:"latest_document_update",fieldsFromTheirs:v.fields_from_theirs,unionFields:v.union_fields,mergedFieldHashes:Object.fromEntries(N.map(O=>[O,Rl(O==="body"?_.body:A[O])])),decisions:v.conflict_decisions,operation:await Pl(process.cwd(),e.itemPath,s)}}}else{let y=Fl(i,s,a,{preferred:o});c=y.merged,d.push(...y.conflict_paths),m.json={paths_from_theirs:y.paths_from_theirs}}if(await Um(r,c,"utf8"),l!==void 0){let y=await Ll(l);y!==null&&(m.receipt=Ue(y))}let g=[];if(d.length>0){let y=m.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${m.receipt.receipt_id} with item ${m.receipt.item_id}; clone-local discarded values are never copied into this result.`;g.push(`Both branches changed ${d.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${y} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&m.history?.reanchored&&g.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:d.length===0,artifact:n,output_path:r,requested_preference:o,conflicts:d,...m,guidance:g,generated_at:S()}}async function zm(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Nl(e.cwd,n.item_path,n.operation))continue;let o={gitWorkspaceRoot:e.cwd,receipt:n};await Ee(n.item_id,{dryRun:!0,mergeAbandonmentProof:o},e.global),e.dryRun||(await Ee(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:o,message:e.message??`Settle ${n.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...Ue(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Bn(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as Uh}from"node:fs/promises";import qh from"node:path";var zh=4;function Hm(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,o=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,r=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,s=Array.isArray(r)?r.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:o,truncated:i,coordinates:s}}async function Hh(e,t){let n=[];for(let o of t){let r;try{r=await Uh(qh.join(e,"history",`${o.item_id}.jsonl`),"utf8")}catch{continue}let i=r.split(/\r?\n/)[o.history_line-1];if(i===void 0||i.trim().length===0)continue;let s;try{s=JSON.parse(i)}catch{continue}let a=ql(s,o.item_id).find(c=>c.receiptId===o.receipt_id);a===void 0||!Ul(a)||a.eventTimestamp===void 0||ps(a.eventTimestamp,Gl)>=0||n.push({...o,original_event_ts:a.eventTimestamp})}return n}async function Bh(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let o=t.get(n.item_id)??[];o.push(n),t.set(n.item_id,o)}for(let[n,o]of t)await Ee(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:o.map(r=>({receipt_id:r.receipt_id,original_history_line:r.history_line,original_event_ts:r.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function Wh(e){try{return{status:"fulfilled",value:await Ee(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function Vh(e){e.results.forEach((t,n)=>{let o=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let r=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:o,outcome:r,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[r]+=1;return}e.repair.streams.push({id:o,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function Kh(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(o=>o.merge_receipt_proof?.trusted?o.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(o=>t.has(o.id));return await Promise.all(n.map(o=>Bn(e.receiptWorkspaceRoot,o,{requireExisting:!0}))),n.length}function Jh(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function Yh(e,t){if(e.force===!0)throw new p("Automatic staging cannot accept forced reconciliation.",u.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let n={...e,stage:!1},{stageLosslessMergeReconciliation:o,resolveMergeSettlementGlobal:r}=await import("./stage-UIDZMTE5.js"),i=await r(t),s=await lo({...n,dryRun:!0},i);return o({preview:s,dryRun:e.dryRun===!0,global:i,apply:()=>lo({...n,dryRun:!1},i)})}async function lo(e,t){return e.stage===!0?Yh(e,t):Xh(e,t)}async function Xh(e,t){let n=e.dryRun===!0,o=x(process.cwd(),t.path),r=await Vt(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Hm(r),s=await Hh(o,i.coordinates),a=await Yc(o),c=a??o,l=await Ml(c,{includeLossless:!0,pmRoot:o});if(l.invalid_evidence_count>0)throw new p(`Merge reconciliation refused ${l.invalid_evidence_count} invalid receipt evidence file(s).`,u.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});Dl(l.receipts.map(L=>L.id),l,n);let d=await Bh({candidates:s,options:e,global:t}),m=l.receipts,f=await zm({cwd:a,receipts:m,dryRun:n,author:e.author,message:e.message,global:t}),g=new Set(f),y=new Map;for(let L of m.filter(ve=>!g.has(ve.id))){let ve=y.get(L.item_id)??[];ve.push(L),y.set(L.item_id,ve)}let k=Object.fromEntries([...y].map(([L,ve])=>[L,{merge:{receipts:ve.map(Ue)}}])),b=Object.fromEntries([...y].map(([L,ve])=>[L,{gitWorkspaceRoot:a,receipts:ve}])),v=await Wn({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:k,...m.length>0?{mergeReceiptProofById:b}:{}},t),_=new Set(v.streams.map(L=>L.id)),A=[...y.keys()].filter(L=>!_.has(L)),N=await Pa(A,zh,L=>Wh({id:L,dryRun:n,options:e,global:t,auditContext:k[L],mergeReceiptProof:b[L]}));Vh({receiptOnlyIds:A,results:N,repair:v});let O=await Kh({dryRun:n,pendingReceipts:m,repair:v,receiptWorkspaceRoot:c}),B=await Vn({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),$=d===0?r:await Vt(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),R=Hm($),ie=B.checks.every(L=>L.status==="ok"),Tt=n?m.length===0:O+f.length===m.length,ne=[v.totals.failed===0,ie,Tt,R.count===0,!R.truncated].every(Boolean),Ve=i.truncated||R.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,Ke=Jh(m.length,ne),Su=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",Ve,Ke,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:ne?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",Ve,Ke,...s.length>0&&d===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(L=>L!==void 0);return{ok:ne,dry_run:n,repair:v,receipts:{pending_before:m.length,reconciled:O,abandoned:f.length,summaries:m.map(Ue),unstaged_durable_receipt_ids:l.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:d,missing_history_references_after:R.count},validation:B,guidance:Su,generated_at:B.generated_at}}var Zh="1h",Qh="now",eg="+1d";function Te(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Bm(e,t,n){let o={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,inheritFocus:n.inheritFocus,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return le(n,o)}async function Wm(e,t,n,o){let r=Bm(e,t,n),i=[];return Te(i,"start",n.start??Qh),n.end!==void 0?Te(i,"end",n.end):Te(i,"duration",n.duration??Zh),Te(i,"location",n.location),Te(i,"timezone",n.timezone),n.allDay===!0&&Te(i,"all_day","true"),r.event=[i.join(",")],Ce(r,o)}function Vm(e,t,n){return Wm("Meeting",e,t,n)}function Km(e,t,n){return Wm("Event",e,t,n)}function Jm(e,t,n){let o=Bm("Reminder",e,t),r=[];return Te(r,"at",t.at??eg),Te(r,"text",t.text??e),o.reminder=[r.join(",")],Ce(o,n)}function en(e){let t={...e.args,...e.options};return le(e.options,t)}function ye(e,t){let n=h(e,t);if(n!==void 0)return n;throw new p(`Missing required parameter: ${t}`,u.USAGE)}function ft(e){return typeof e=="string"?[e]:U(e)}function Ym(e){return ld(en(e),e.global)}function Xm(e){let t=en(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new p("Mutation event cursor mode must be batch or row.",u.USAGE,{code:"invalid_event_cursor_mode"});let o=n;return dd({cwd:h(t,"cwd"),pmRoot:h(t,"path"),since:h(t,"since"),type:ft(t.type),author:ft(t.author),item:ft(t.item),limit:t.limit===void 0?void 0:X(t.limit,"limit"),full:t.full===!0,...t.verify===!0?{verify:!0}:{},...o===void 0?{}:{cursorMode:o},...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:ft(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:ft(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:ft(t.provenanceFilter)}})}function Zm(e){let t=en(e),n=ye(t,"subcommand");if(n==="install")return Xc({dryRun:t.dryRun===!0,preCommitHook:t.preCommitHook===!0},e.global);if(n==="reconcile")return lo({dryRun:t.dryRun===!0,author:h(t,"author"),message:h(t,"message"),force:t.force===!0,stage:t.stage===!0},e.global);if(n==="report")return jl({includeReconciled:t.includeReconciled===!0,cwd:h(t,"cwd")});if(n==="driver")return qm({artifact:ye(t,"artifact"),basePath:ye(t,"basePath"),oursPath:ye(t,"oursPath"),theirsPath:ye(t,"theirsPath"),outputPath:h(t,"outputPath")??h(t,"output"),itemPath:h(t,"itemPath"),prefer:h(t,"prefer")},e.global);throw ae({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Qm(e){let t=en(e),n=ye(t,"subcommand");if(n==="position")return gd(e.global);if(n!=="snapshot")throw ae({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let o=h(t,"snapshotAction")??ye(t,"snapshot_action"),r=x(process.cwd(),e.global.path);if(o==="create")return md(r,{name:h(t,"name")});if(o==="list")return ud(r);let i=ye(t,"target");if(o==="inspect")return pd(r,i);if(o==="delete")return hd(r,i);if(o==="restore")return t.dryRun===!0?fd(r,i):_d(r,i,{force:t.force===!0,author:h(t,"author"),message:h(t,"message"),lockTtlSeconds:X(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:X(t.lockWaitMs,"lockWaitMs")});throw ae({command_path:"workspace snapshot",token:o,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function mo(e){let t=en(e),n=ye(t,"title");return e.action==="meet"?Vm(n,t,e.global):e.action==="event"?Km(n,t,e.global):Jm(n,t,e.global)}function ep(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:h(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:U(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:h(e,"measurementSource"),measurementItem:h(e,"measurementItem"),measurementRevision:h(e,"measurementRevision"),author:h(e,"author"),message:h(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:h(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}function tp(e,t,n){let o;if(typeof e.lines=="string")o=dr(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");o=dr(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:o,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}function K(e,t){let n=h(e,t);if(!n)throw new p(`Missing required argument: ${t}`,64);return n}function be(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function tg(e){let t=h(e.args,"subcommand")??K(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:h(e.args,"name")??h(e.options,"name"),author:h(e.args,"author")??h(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:U(n)}}function ng(e){let{ctx:t,subcommand:n,name:o,author:r,force:i}=e,a=be({list:()=>cl(t.global),show:()=>ll(o,t.global),"show-status":()=>dl(o,t.global),"list-fields":()=>ul(t.global),"show-field":()=>fl(o,t.global),"remove-type":()=>rl(o,{author:r,force:i},t.global),"remove-field":()=>pl(o,{author:r,force:i},t.global),"remove-status":()=>al(o,{author:r,force:i},t.global),"apply-preset":()=>_l(h(t.args,"typePreset")??h(t.options,"typePreset"),{author:r,force:i},t.global)},n);return a?a():null}function og(e){let{ctx:t,name:n,author:o,force:r,aliases:i}=e,s=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return ml(n,{type:h(t.args,"fieldType")??h(t.options,"fieldType"),commands:s===void 0?void 0:U(s),description:h(t.args,"description")??h(t.options,"description"),cliFlag:h(t.args,"cliFlag")??h(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:U(a),author:o,force:r},t.global)}function rg(e){let{ctx:t,name:n,author:o,force:r,aliases:i}=e,s=t.args.role??t.options.role;return sl(n,{role:s===void 0?void 0:U(s),alias:i,description:h(t.args,"description")??h(t.options,"description"),order:X(t.args.order??t.options.order,"schema add-status order"),author:o,force:r},t.global)}function ig(e){let{ctx:t,name:n,author:o,force:r,aliases:i}=e;return ol(n,{description:h(t.args,"description")??h(t.options,"description"),defaultStatus:h(t.args,"defaultStatus")??h(t.args,"default_status")??h(t.options,"defaultStatus")??h(t.options,"default_status"),folder:h(t.args,"folder")??h(t.options,"folder"),alias:i,author:o,force:r},t.global)}function sg(e){let{ctx:t,subcommand:n,name:o,author:r,force:i}=e,s=h(t.args,"to")??K(t.options,"to"),a=h(t.args,"migrationId")??h(t.args,"migration_id")??h(t.options,"migrationId")??h(t.options,"migration_id"),c=h(t.args,"fieldTypeScope")??h(t.options,"fieldTypeScope")??h(t.args,"type")??h(t.options,"type"),l=n==="rename-type"?{kind:"rename-type",from:o??"",to:s}:n==="rename-field"?{kind:"rename-field",from:o??"",to:s,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:o??"",to:s};return tl(l,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:r,force:i},t.global)}function np(e){let t=tg(e);Xi(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=dn.find(r=>r===t.subcommand);if(n)return el(n,t.name,{definition:e.args.definition??e.options.definition,policy:h(e.args,"policy")??h(e.options,"policy"),message:h(e.args,"message")??h(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let o=ng(t);if(o!==null)return o;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return sg(t);if(t.subcommand==="add-field")return og(t);if(t.subcommand==="add-status")return rg(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?hl({minCount:X(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):ig(t);throw ae({command_path:"schema",token:t.subcommand,allowed:nl,exit_code:64})}function po(e){return h(e.args,"target")??h(e.options,"target")}function q(e,t=e.options){return e.id??K(t,"id")}async function ag(e){let t=Qe("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Nr(await _e(h(e.args,"status")??h(t,"status"),t,e.global),t)}async function cg(e){let t=h(e.args,"query")??h(e.args,"keywords")??K(e.args,"query"),n=Qe("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Nr(await Ar(t,n,e.global),n)}async function lg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await Ce(o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function dg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r={...o,...o.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...o.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return H(await Dr(q(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function mg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await lt(q(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function pg(e){let t=Me(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0),Nd(q(e),t,e.global)}function op(e,t){return El(tp(e.options,t,X),e.global)}function ug(e){let t=U(e.options.lookupPath);if(t&&t.length>0)return op(e,t);let n=q(e);return e.options.discover===!0?mr(n,Mn(e.options),e.global):Il(n,Wt(Me(e.options)),e.global)}function fg(e){return yd({subcommand:h(e.args,"subcommand")??h(e.options,"subcommand"),limit:Lc(e.args,e.options)},e.global)}function _g(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Vt(e.global,t)}function hg(e){let t=h(e.args,"configAction")??h(e.options,"configAction")??h(e.options,"action");if(t===void 0)throw new p("Missing required argument: configAction",64);let n=h(e.args,"value")??h(e.options,"value"),o=h(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options,r=h(e.args,"key")??h(e.options,"key");return kl(h(e.args,"scope")??h(e.options,"scope")??Zs(r),t,r,o,e.global,h(e.options,"policy")===void 0?n:void 0)}function gg(e){let t=e.options;return od(nd(t),e.global)}function yg(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new p(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new p(`${t} must be a finite integer.`,64);let o=Number.parseInt(n,10);if(!Number.isInteger(o))throw new p(`${t} must be a finite integer.`,64);return o}}async function bg(e){let t=h(e.args,"subcommand")??K(e.options,"subcommand"),n=e.options,{changedFields:o,idOnly:r}=j(e.args,e.options),i=await am({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:wg(e),reorderTo:yg(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&rr(e.args)&&(i.mutation_receipt=oo(i,void 0)),t==="show"?i:H(i,{changedFields:o,idOnly:r,compactEnvelope:o==="compact"&&!r})}function wg(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function vg(e){let t=h(e.args,"subcommand")??K(e.options,"subcommand"),n=t.trim().toLowerCase(),o=h(e.args,"name")??h(e.options,"name"),i=be({list:()=>Nm(),show:()=>Lm(o),lint:()=>Mm(o),apply:()=>Dm(o,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:h(e.args,"author")??h(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!i)throw ae({command_path:"profile",token:t,allowed:Pm,exit_code:64});return i()}async function kg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options);return H(await Gd(q(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Sg(e){let{changedFields:t,runnerOptions:n}=j(e.args,e.options);return H(await pm(jn(n,!rr(e.args)),e.global),{changedFields:t})}async function Ag(e){let{changedFields:t,runnerOptions:n}=j(e.args,e.options),o=h(e.args,"reason"),r=o!==void 0&&n.reason===void 0?{...n,reason:o}:{...n};return e.force&&r.force===void 0&&(r.force=!0),H(await Hd(Dn(r),e.global),{changedFields:t})}async function xg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=j(e.args,e.options),r=h(o,"target")??K(e.args,"target");return H(await vr(q(e,o),r,o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Ig(e){let t={...e.args,...e.options};return Cl(K(t,"subcommand"),h(t,"id")??e.id,h(t,"target"),Uc(t),e.global)}function Eg(e){return bl(x(process.cwd(),e.global.path),{...e.args,...e.options})}var gi={init:e=>yl(h(e.args,"prefix"),e.global,e.options),context:e=>hr(Qe("context",e.options),e.global),next:e=>gr(Qe("next",e.options),e.global),eval:Ym,events:Xm,merge:Zm,workspace:Qm,meet:mo,event:mo,remind:mo,list:ag,get:e=>{let t=q(e);return Sr(t,e.global,Qe("get",e.options,[t]))},search:cg,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:U(e.options.status);return lr(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:h(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:X(e.options.limit,"limit")})},create:lg,copy:dg,focus:e=>Gr(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:mg,"item-reopen":Jd,restore:xg,claim:Wd,release:Kd,"start-task":e=>ze(e,"start_task"),"pause-task":e=>ze(e,"pause_task"),"close-task":e=>ze(e,"close_task"),close:Vd,comments:pg,notes:e=>fm(q(e),Me(e.options),e.global),learnings:e=>Dd(q(e),Me(e.options),e.global),files:ug,docs:e=>Al(q(e),Wt(Me(e.options)),e.global),test:e=>bd(q(e),Me(e.options),e.global),"test-all":e=>wd(e.options,e.global),telemetry:fg,validate:e=>Vn(e.options,e.global,{runUpdate:(t,n,o)=>lt(t,n,o)}),health:_g,assurance:e=>Hl(e.args,e.options,e.global),contracts:e=>Gn(e.options,e.global),config:hg,activity:gg,aggregate:e=>kr(e.options,e.global),extension:e=>zn(po(e),e.options,e.global),package:e=>zn(po(e),e.options,e.global),install:e=>zn(po(e),{...e.options,install:!0},e.global),upgrade:e=>Wl(po(e),e.options,e.global),delete:e=>jr(q(e),e.options,e.global),deps:e=>Sl(q(e),e.options,e.global),graph:Ig,"files-discover":e=>mr(q(e),e.options,e.global),"files-lookup":e=>op(e,U(e.options.paths)),history:e=>cd(q(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Yl(q(e),e.options,e.global),"history-repair":Ld,"history-compact":Md,"history-attest":e=>Xl(e.options,e.global),"history-author-acknowledge":Eg,plan:bg,schema:np,profile:vg,stats:e=>xr(e.global,ep(e.options)),append:kg,"update-many":Sg,"close-many":Ag,gc:e=>Bl(e.global,e.options)};var Oe=new Map;function yi(){Oe.clear()}function rp(e,t){let n=Oe.get(e);if(n!==void 0)return n;if(Oe.size>=50){let r=Oe.keys().next().value;Oe.delete(r)}let o=t().catch(r=>{throw Oe.get(e)===o&&Oe.delete(e),r});return Oe.set(e,o),o}var Xx=Ui,Zx=qi,Qx=Bi,eI=zi,tI=Hi;function ip(e,t,n,o){let r=e.flag.slice(2).replace(/[-_]([a-z])/gu,(s,a)=>a.toUpperCase()),i=n.has(r);return{long:t,...o?{short:o}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:i?"string":"boolean",...i?{value_name:e.value_name??"value"}:{}}}function sp(e,t=[]){let n=new Set(t.flatMap(r=>r.keys)),o=[];for(let r of qa(e.map(i=>({...i})))){o.push(ip(r,r.flag,n,r.short));for(let i of r.aliases??[])o.push(ip(r,i,n))}return o}var nI=sp(Pn,xc),Cg=sp(Nn,Ic);import lp from"node:path";function ap(e){return e.map(t=>({key:t.key,optionName:ws(t),metadataKey:t.metadata_key,type:t.type,commands:[...t.commands],repeatable:t.repeatable,requiredOnCreate:t.required_on_create,...t.description?{description:t.description}:{}}))}function cp(e){return e.map(t=>({command:t.command,action:t.action,arguments:t.arguments.map(n=>({name:n.name,required:n.required===!0,variadic:n.variadic===!0,description:n.description})),description:t.description,tier:t.tier??"standard",family:t.family??"extensions"}))}function Rg(e,t,n){return JSON.stringify([lp.resolve(e),lp.resolve(n??process.cwd()),t.extensions.enabled,t.extensions.disabled,t.extensions.policy])}async function Tg(e,t,n){let o=Rg(e,t,n);return rp(o,()=>$g(e,t,n))}async function Og(e,t={}){let n=await I(e),o=t.extensionRegistrations??(t.noExtensions===!0?null:await Tg(e,n,t.cwd)),r=F(n,o),i=W(n.schema),s=Xe(n.schema);return{types:[...r.types],statuses:i.definitions.map(a=>a.id),openStatus:i.open_status,closeStatus:i.close_status,canceledStatus:i.canceled_status,fields:ap(s.definitions),extensionCommands:cp(o?.commands??[])}}async function $g(e,t,n){let o=await kn({pmRoot:e,settings:t,cwd:n??process.cwd(),noExtensions:!1}),r=await An(o);try{return r.registrations}finally{try{await Sn(o,r)}catch{}}}var Fg=new Set(["true","1","yes","on"]),Pg=new Set(["false","0","no","off"]);function Ng(e,t,n=[]){let o=[t,...n];for(let r of o){let i=e[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}}function Lg(e,t,n=[]){let o=[t,...n];for(let r of o){let i=e[r];if(i!==void 0){if(typeof i=="boolean")return i;if(typeof i=="string"){let s=i.trim().toLowerCase();if(Fg.has(s))return!0;if(Pg.has(s))return!1}}}}function Mg(e,t,n=[]){for(let o of[t,...n]){let r=e[o],s=(typeof r=="string"?r.split(","):Array.isArray(r)?r.flatMap(a=>typeof a=="string"?a.split(","):[]):[]).map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}return[]}function z(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Dg(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t)&&t>=0)return t}}function jg(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=4)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isInteger(t)&&t>=0&&t<=4)return t}return 2}function Gg(e){if(Array.isArray(e)){let t=e.filter(n=>typeof n=="string").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return Array.from(new Set(t)).sort((n,o)=>n.localeCompare(o))}return typeof e=="string"?$t(e):[]}function Ug(e){let t=z(e);if(t){let n=Ne(t);if(n)return n}return"open"}function wi(e){if(typeof e=="number"&&Number.isInteger(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isInteger(t)?t:void 0}function dp(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e===1?!0:e===0?!1:void 0;if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:void 0}function _t(e){if(!Array.isArray(e))return;let t=e.map(n=>z(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}function bi(e){return up(e,z)}function mp(e){return up(e,_p)}function qg(e,t){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=100)return e;let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;if(t.some(i=>i===o))return o;let r=Number(o);return Number.isInteger(r)&&r>=0&&r<=100?r:void 0}function pp(e,t){let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;return t.includes(o)?o:void 0}function vi(e){return z(e)?.toLowerCase()==="global"?"global":"project"}function zg(e,t){let n=ki(e,t.allowScalar===!0);if(!n)return;let o=n.map(r=>Jg(r,t)).filter(r=>r!==void 0);return o.length>0?o:void 0}function Hg(e,t={}){return fp(e,t,(n,o)=>({path:n,scope:vi(o?.scope),note:z(o?.note)}))}function Bg(e,t={}){return fp(e,t,(n,o)=>({path:n,scope:vi(o?.scope),note:z(o?.note)}))}function Wg(e){let t=(Array.isArray(e)?e:[]).filter(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof o.field=="string"&&ks(o.field)!==void 0&&typeof o.reason=="string"&&o.reason.trim().length>0),n=new Map(t.map(o=>[o.field,{field:o.field,reason:o.reason}]));return As([...n.values()])}function Vg(e,t={}){let n=ki(e,t.allowScalar===!0);if(!n)return;let o=n.map(r=>Zg(r,t)).filter(r=>r!==void 0);return o.length>0?o:void 0}function Kg(e,t){return C(e,t)}function fo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ki(e,t){return Array.isArray(e)?e:t?[e]:void 0}function uo(e,t){for(let n of t){let o=z(e[n]);if(o)return o}}function up(e,t){if(!fo(e))return;let n=Object.entries(e).map(([o,r])=>[o.trim(),t(r)]).filter(o=>o[0].length>0&&o[1]!==void 0);return n.length>0?Object.fromEntries(n):void 0}function Jg(e,t){if(typeof e=="string")return Yg(e,t);if(!fo(e))return;let n=uo(e,t.textKeys??["text"]);if(!n)return;let o=t.createdAtKey??"created_at",r=t.authorKey??"author";return{created_at:(t.toIsoString?t.toIsoString(e[o]):z(e[o]))??t.fallbackCreatedAt,author:z(e[r])??t.fallbackAuthor,text:n}}function Yg(e,t){let n=z(e);return n?{created_at:t.fallbackCreatedAt,author:t.fallbackAuthor,text:n}:void 0}function fp(e,t,n){let o=ki(e,t.allowScalar===!0);if(!o)return;let r=t.pathKeys??["path"],i=o.map(s=>Xg(s,r,n)).filter(s=>s!==void 0);return i.length>0?i:void 0}function Xg(e,t,n){if(typeof e=="string"){let r=z(e);return r?n(r):void 0}if(!fo(e))return;let o=uo(e,t);return o?n(o,e):void 0}function Zg(e,t){if(typeof e=="string"){let r=z(e);return r?{command:r,scope:"project"}:void 0}if(!fo(e))return;let n=uo(e,t.commandKeys??["command"]),o=uo(e,t.pathKeys??["path"]);if(!(!n&&(t.requireCommand===!0||!o)))return{...n?{command:n}:{},...o?{path:o}:{},scope:vi(e.scope),timeout_seconds:Qg(e.timeout_seconds,t),note:z(e.note),...typeof e.phase=="string"&&e.phase.trim().toLowerCase()==="setup"?{phase:"setup"}:{},...t.includeExtendedAssertions===!0?ey(e):{}}}function Qg(e,t){let n=t.integerTimeout===!0?wi(e):_p(e);if(n===void 0)return;let o=t.timeoutMinimum??0;return t.timeoutExclusiveMinimum===!0?n>o?n:void 0:n>=o?n:void 0}function _p(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function ey(e){return{pm_context_mode:pp(e.pm_context_mode,["schema","tracker","auto"]),env_set:bi(e.env_set),env_clear:_t(e.env_clear),shared_host_safe:dp(e.shared_host_safe),assert_stdout_contains:_t(e.assert_stdout_contains),assert_stdout_regex:_t(e.assert_stdout_regex),assert_stderr_contains:_t(e.assert_stderr_contains),assert_stderr_regex:_t(e.assert_stderr_regex),assert_stdout_min_lines:wi(e.assert_stdout_min_lines),assert_json_field_equals:bi(e.assert_json_field_equals),assert_json_field_gte:mp(e.assert_json_field_gte)}}async function ty(e){await P(e)}function hp(){return{metadata:{},body:""}}function ny(e){return[...Object.entries(e.metadata).filter(([,n])=>n!==void 0).map(([n])=>n),...e.body.length>0?["body"]:[]].sort()}async function oy(e){let{pmRoot:t,id:n,itemPath:o,author:r,message:i,settings:s,conflictWarningPrefix:a}=e,c={...e.document,metadata:{...e.document.metadata}};Ss(c.metadata),fa(c.metadata,t);let l=Mt(c),d=me(t,n),m=hp(),f;try{f=await Dt(t,n,s.locks.ttl_seconds,r,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(g){if(g instanceof p&&g.exitCode===u.CONFLICT)return{committed:!1,conflictWarning:`${a}:${n}`};throw g}try{let g=F(s,T()).type_to_folder;if(await oe(t,n,s.id_prefix,s.item_format,g))return{committed:!1,conflictWarning:`${a}:${n}`};let y=await Rn({pmRoot:t,settings:s,operation:"import",author:r,before:null,after:l});return await xn({pm_root:t,operation:"import",before:null,after:l,changed_fields:ny(l),author:r,sdk:On({pmRoot:t,settings:s,typeToFolder:g})}),await f.fence(async()=>{await se(o,Lt(l,{format:"toon"}));try{let b=jt({nowIso:S(),author:r,op:"import",before:m,after:l,message:i,context:y.decisions.length===0?void 0:{workflow_policies:y.decisions}});await Gt(d,b)}catch(b){throw await Ft(o),b}}),{committed:!0,writeWarnings:[...y.warnings,...await G({path:o,scope:"project",op:"import",item_id:l.metadata.id,item_type:l.metadata.type,before:m,after:l,changed_fields:["imported"]}),...await G({path:d,scope:"project",op:"import:history",item_id:l.metadata.id,item_type:l.metadata.type,before:m,after:l,changed_fields:["imported"]})]}}finally{await f.release()}}import{readFile as iy}from"node:fs/promises";import sy from"node:path";function ry(e){return e.trim().toLowerCase().replaceAll("_","-")}var Ai=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:Kc().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks (repository checkout only; excluded from the npm package).",optional:!0},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes (repository checkout only; excluded from the npm package).",optional:!0},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering (repository checkout only; not in the npm package).",optional:!0}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],Si=new Map;for(let e of Ai){Si.set(e.id,e);for(let t of e.aliases)Si.set(t,e)}function gp(){return Ai.map(e=>({...e,aliases:[...e.aliases],commands:[...e.commands],workflows:e.workflows.map(t=>({...t,commands:[...t.commands]})),docs:e.docs.map(t=>({...t})),related:[...e.related]}))}function _o(){return Ai.map(e=>e.id)}function yp(e){if(!e)return null;let t=ry(e);return t?Si.get(t)??null:null}var ay=["markdown","toon","json"],cy=["brief","standard","deep"];function ly(e){if(!e)return;let t=e.trim().toLowerCase();if(!ay.includes(t))throw new p("Guide format must be one of markdown|toon|json",u.USAGE);return t}function dy(e,t){let n=ly(e.format);if(t.json&&n&&n!=="json")throw new p("Cannot combine --json with --format markdown|toon",u.USAGE);return t.json?"json":n??"toon"}function my(e){if(!e)return"brief";let t=e.trim().toLowerCase();if(!cy.includes(t))throw new p("Guide depth must be one of brief|standard|deep",u.USAGE);return t}function py(){return js(process.env,"PM_CLI_PACKAGE_ROOT",import.meta.url,["..","..",".."])}function bp(e){return e.replaceAll(`\r
71
71
  `,`
72
- `)}function my(e,t,n){let r=yp(e).split(`
72
+ `)}function uy(e,t,n){let r=bp(e).split(`
73
73
  `),s=r.slice(0,t).join(`
74
- `),a=r.length>t;return s.length>n&&(s=s.slice(0,n),a=!0),{excerpt:s.trimEnd(),truncated:a,lineCount:r.length}}async function py(e,t,n){let o=t!=="brief",r=o?t==="deep"?"full":"excerpt":"none",i=[];for(let s of e.docs){let a=ry.resolve(n,s.path);if(!o){i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!0,line_count:null,content_mode:"none",content:null,truncated:!1});continue}try{let c=await oy(a,"utf8");if(t==="deep"){let l=yp(c).trimEnd();i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!0,line_count:l.length===0?0:l.split(`
75
- `).length,content_mode:"full",content:l,truncated:!1})}else{let l=my(c,120,12e3);i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!0,line_count:l.lineCount,content_mode:r,content:l.excerpt,truncated:l.truncated})}}catch(c){let l=Je(c);if(i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!1,line_count:null,content_mode:"none",content:null,truncated:!1}),!l)throw new p(`Failed to read guide document "${s.path}".`,u.GENERIC_FAILURE)}}return i}function uy(e){let t=hp().map(n=>({id:n.id,aliases:n.aliases,title:n.title,summary:n.summary,intent:n.intent,quick_commands:e==="brief"?n.commands.slice(0,3):n.commands.slice(0,6),docs:n.docs.map(o=>({path:o.path,purpose:o.purpose})),related:n.related}));return{output_default:"toon",mode:"index",depth:e,topics:t,suggested_next_steps:["pm guide <topic>","pm guide <topic> --depth standard","pm guide <topic> --depth deep --format markdown","pm guide <topic> --json"]}}function fy(e){let t=gp(e);if(t)return t;let n=_o().join(", ");throw new p(`Unknown guide topic "${e}". Available topics: ${n}. Use "pm guide --list" to browse.`,u.USAGE)}async function _y(e,t){let n=ly(typeof e.depth=="string"?e.depth:void 0),o=e.list===!0,r=typeof e.topic=="string"?e.topic:void 0;if(o||!r)return uy(n);let i=fy(r),s=dy(),a=await py(i,n,s),c=a.filter(l=>!l.exists&&!l.optional).map(l=>`Missing required guide document: ${l.path}`);return{output_default:"toon",mode:"topic",depth:n,requested_topic:r,topic:i,docs:a,warnings:c}}function hy(e){return e.replaceAll("```","``\\`")}function gy(e){if(e.mode==="index"){let n=["# pm guide","","Token-efficient local documentation index for agent and maintainer workflows.","","## Topics"];for(let o of e.topics)n.push(`- \`${o.id}\` - ${o.summary}`),e.depth!=="brief"&&(n.push(` - intent: ${o.intent}`),n.push(` - docs: ${o.docs.map(r=>`\`${r.path}\``).join(", ")}`));n.push("","## Next steps");for(let o of e.suggested_next_steps)n.push(`- \`${o}\``);return n.join(`
76
- `)}let t=[`# pm guide ${e.topic.id}`,"",e.topic.summary,"","## Intent",e.topic.intent,"","## Key commands",...e.topic.commands.map(n=>`- \`${n}\``),"","## Workflow prompts"];for(let n of e.topic.workflows)t.push(`### ${n.name}`),t.push(`goal: ${n.goal}`),t.push(`prompt: ${n.prompt}`),t.push("commands:"),t.push(...n.commands.map(o=>`- \`${o}\``)),t.push("");t.push("## Documents");for(let n of e.docs){let o=n.exists?"available":n.optional?"missing (optional)":"missing (required)";t.push(`- \`${n.path}\` - ${n.purpose} (${o})`),n.exists&&n.content_mode!=="none"&&n.content&&(t.push(""),t.push(`### Excerpt: \`${n.path}\``),n.truncated&&t.push("_truncated for context efficiency_"),t.push("```markdown"),t.push(hy(n.content)),t.push("```"))}return e.topic.related.length>0&&(t.push("","## Related topics"),t.push(...e.topic.related.map(n=>`- \`${n}\``))),e.warnings.length>0&&(t.push("","## Warnings"),t.push(...e.warnings.map(n=>`- ${n}`))),t.join(`
77
- `)}var yy=[...Pt],by=[...Io],tn=new Set(Vi.filter(e=>e.hidden).map(e=>e.alias)),nn=Vc("full").filter(e=>!e.includes(" ")&&!tn.has(e)),bp=E(Fn),wp=E(qa),vp=E(Xa),kp=E(rc),ho=nr("restore",Ie("restore")),go=nr("history-attest",Ie("history-attest")),Sp=E(ic),Ap=E(Za),xp=E(Qa),Ip=E(oc),Ep=E(mc),Cp=E(sc),Rp=E(ac),Tp=E(Ya),ht=[...new Set(J.map(e=>e.canonical_argv[0]))],on=[...new Set(J.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],wy=new Set(ja.filter(e=>e.disposition==="package_owned").map(e=>So(e.command))),Op=J.filter(e=>e.canonical_argv[0]==="history"),$p=Op.map(e=>e.canonical_argv[1]).join(" ");function gt(e){let t=new Set((e.namespace_commands??[]).map(So)),n=J.filter(o=>Wc(o.canonical)!=="internal"&&(!wy.has(o.alias)||t.has(o.alias)));return Object.fromEntries(on.map(o=>[o,[...new Set(n.filter(r=>r.canonical.startsWith(`${o} `)).map(r=>r.canonical_argv[o.split(" ").length]))].join(" ")]))}var Fp=Op.map(e=>({...e,flags:E(Ie(e.alias))})),xi=E(za),Pp=E(Ha,!1),Np=E(lc),Lp=E(cc),Mp=E(dc),Dp=E(_c),jp=E(uc),Gp=E(tc),Up=E(fc),qp=E(pc),zp=E(Pn),Hp=E(ec),Bp=E(nc),Wp=E(Wa),Vp=E(hc),Kp=E(Ba),yt=`${dn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`,Jp="create show add-step update-step complete-step block-step reorder-step remove-step link unlink decision discovery validation resume approve materialize",vy=E(gc),Yp=`${vy} bash zsh fish`,bt=we(_o()),Be="init scaffold install uninstall list inventory explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",wt=`${Be} upgrade`,Xp=E(Va),Zp=E(Ka),Qp=E(Ja),Ii="--author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",eu="--dry-run --author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",tu=E(Ie("close")),nu=E(Ie("close-task")),ou=E(Ie("release")),ru=E(Ie("claim")),yo=[["workspace","Workspace initialization, customization, state and snapshots"],["init","Initialize pm storage for the current workspace"],["config","Read or update pm settings"],["package","Manage package lifecycle operations"],["packages","Alias for package"],["create","Create a new project management item"],["item","Manage item evidence, links, tests, and duplication"],["copy","Copy an existing item to a new ID"],["focus","Set/clear/show the session focused parent for new items"],["list","List active items with optional filters"],["aggregate","Aggregate grouped item counts and numeric stats for governance queries"],["duplicates","Find bounded duplicate clusters across lifecycle statuses"],["guide","Browse local progressive-disclosure guides"],["calendar","Show calendar views for deadlines and reminders"],["cal","Alias for calendar"],["context","Show a token-efficient project context snapshot"],["ctx","Alias for context"],["get","Show item details by ID"],["next","Recommend the next actionable (unblocked, ready) work item"],["search","Search items with keyword, semantic, or hybrid modes"],["reindex","Rebuild search artifacts"],["history","Show item history entries"],["history-compact","Compact history streams into a synthetic baseline + retained tail"],["history-redact","Redact and reseal item history."],["history-repair","Re-anchor a drifted history chain so pm health/validate report ok"],["schema","Manage custom item types and statuses in .agents/pm/schema/*.json"],["profile","List, show, apply, and lint project profiles (archetype schema/config/template/package bundles)"],["plan","Agent-optimized Plan item workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["activity","Show recent activity across items"],["restore","Restore an item to an earlier state"],["update","Update item fields and metadata"],["update-many","Bulk-update matched items with dry-run and rollback checkpoints"],["close","Close an item (reason requirement follows governance settings)"],["close-many","Bulk-close matched items with an optional shared reason and rollback checkpoint"],["delete","Delete an item and record the change"],["append","Append text to an item body"],["comments","List or add comments for an item"],["notes","List or add notes for an item"],["learnings","List or add learnings for an item"],["files","Manage linked files"],["docs","Manage linked docs"],["deps","Show dependency relationships for an item"],["graph","Bounded graph traversal, analytics, and governance-audit queries"],["test","Manage linked tests and optionally run them"],["test-all","Run linked tests across matching items"],["test-runs","Manage background linked-test runs"],["stats","Show project tracker statistics"],["health","Show project tracker health checks"],["validate","Run standalone validation checks"],["gc","Clean optional cache artifacts"],["contracts","Show machine-readable command and schema contracts"],["claim","Claim an item for active work"],["release","Release the active claim for an item"],["start-task","Lifecycle alias to claim and set in_progress"],["pause-task","Lifecycle alias to reopen and release claim"],["close-task","Lifecycle alias to close and release claim"],["meet","Shortcut to create a Meeting with scheduling defaults"],["event","Shortcut to create an Event with scheduling defaults"],["remind","Shortcut to create a Reminder from a point in time"],["templates","Manage reusable create templates"],["completion","Generate shell completion"],["help","Display help for a command"]],bo=Ua.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),vt=[...mn].join("|"),kt=[...mn].map(e=>`${e}=*`).join("|"),St=[...bo.split(" ").filter(e=>!mn.has(e)),"-h","-V"].join("|");function we(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}function ky(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].join(" ")}function rn(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll("$","\\$").replaceAll("`","\\`")}function At(e,t){return ky(e.length>0?e:t.item_types??yy)}function xt(e){return we(e.statuses??by)}function $e(e,t){let n=[...e.split(/\s+/u).filter(o=>o.length>0),...t??[]];return we(n)}function wo(e){let t=(e??[]).map(n=>n.trim()).filter(n=>n.startsWith("--")&&n.length>2).map(n=>`--${n.slice(2).replaceAll("_","-")}`);return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function iu(e,t,n){let o=e.toUpperCase(),r=`PM_COMPLETION_${o}_CACHE`,i=`PM_COMPLETION_${o}_CACHE_TS`,s=`PM_COMPLETION_${o}_TTL`,a=rn(n);return[`_pm_completion_${e}_choices() {`," local now ttl cache_ts resolved",' now="$(date +%s 2>/dev/null || echo 0)"',` ttl="\${${s}:-120}"`,` cache_ts="\${${i}:-0}"`,` if [[ -n "\${${r}:-}" && "$now" -ne 0 && $((now - cache_ts)) -lt "$ttl" ]]; then`,` printf '%s\\n' "$${r}"`," return 0"," fi",` resolved="$(pm ${t} 2>/dev/null)"`,' if [[ -z "$resolved" ]]; then',` resolved="${a}"`," fi",` ${r}="$resolved"`,` ${i}="$now"`,` printf '%s\\n' "$${r}"`,"}"]}function Ei(e=[],t=[],n=!1,o={}){let r=gt(o),i=nn.join(" "),s=e.length===0,a=At(e,o),c=xt(o),l=we(t),d=$e(bp,o.command_flags?.list),m=$e(Ip,o.command_flags?.create),f=$e(Cp,o.command_flags?.update),g=$e(Rp,o.command_flags?.["update-many"]),y=$e(zp,o.command_flags?.search),k=$e(Lp,o.command_flags?.calendar),b=$e(Mp,o.command_flags?.context),v=n||t.length>0,_=A=>`_pm_completion_add_matches "${rn(A)}"`;return["# bash completion for pm",`# Source this file or add 'eval "$(pm completion bash)"' to ~/.bashrc`,"",...s?[...iu("type","completion-types",a),""]:[],...iu("status","completion-statuses",c),"","# Treat choices as data: no eval, compgen expansion, or filename globbing.","_pm_completion_add_matches() {"," local line value quoted parse_char parse_index"," local -a values"," while IFS= read -r line; do",' read -r -a values <<< "$line"',' for value in "${values[@]}"; do',' [[ "$value" == "$cur"* ]] || continue',' case "$quote_mode" in'," single)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("$quoted'")`," ;;"," double)"," quoted="," for (( parse_index=0; parse_index<${#value}; parse_index++ )); do",' parse_char="${value:parse_index:1}"',' case "$parse_char" in'," '\"'|'\\'|'$'|'`') quoted=\"${quoted}\\\\${parse_char}\" ;;",` '!') quoted="\${quoted}\\"'!'\\"" ;;`,' *) quoted="${quoted}${parse_char}" ;;'," esac"," done",' COMPREPLY+=("$quoted\\"")'," ;;"," *)",' case "$value" in'," *[!a-zA-Z0-9_.,:/@%+=-]*)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("'$quoted'")`," ;;",' *) COMPREPLY+=("$value") ;;'," esac"," ;;"," esac"," done",' done <<< "$1"',"}","","_pm_completion() {"," local cur prev words cword raw_prefix quote_mode parse_char next_char parse_index quote_start escaped"," COMPREPLY=()",' raw_prefix="${COMP_WORDS[COMP_CWORD]}"'," _init_completion 2>/dev/null || {",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," cword=$COMP_CWORD"," }"," # Decode only the current Readline word. Never evaluate or expand it."," quote_mode=plain escaped=0 quote_start=0 cur="," for (( parse_index=0; parse_index<${#raw_prefix}; parse_index++ )); do",' parse_char="${raw_prefix:parse_index:1}"',' if (( escaped )); then cur="${cur}${parse_char}"; escaped=0; continue; fi',' case "$quote_mode" in'," single)",' if [[ "$parse_char" == "\'" ]]; then quote_mode=plain; else cur="${cur}${parse_char}"; fi'," ;;"," double)",' case "$parse_char" in',` '"') quote_mode=plain ;;`," '\\')",' next_char="${raw_prefix:parse_index+1:1}"',' case "$next_char" in'," '\"'|'\\'|'$'|'`') escaped=1 ;;",' *) cur="${cur}\\\\" ;;'," esac"," ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," *)",' case "$parse_char" in',` "'") quote_mode=single; quote_start=$parse_index ;;`,` '"') quote_mode=double; quote_start=$parse_index ;;`," '\\') escaped=1 ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," esac"," done"," # A mixed quoted segment has a different replacement span; keep it conservative.",' [[ "$quote_mode" != plain && $quote_start -ne 0 ]] && return 0',""," if [[ $cword -eq 1 ]]; then",` ${_(i)}`," return 0"," fi","",' if [[ "$prev" == "--type" ]]; then',s?' _pm_completion_add_matches "$(_pm_completion_type_choices)"':` ${_(a)}`," return 0"," fi","",' if [[ "$prev" == "--status" ]]; then',' _pm_completion_add_matches "$(_pm_completion_status_choices)"'," return 0"," fi","",...v?[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then',` ${_(l)}`," return 0"," fi"]:[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," local now ttl cache_ts tag_values",' now="$(date +%s 2>/dev/null || echo 0)"',' ttl="${PM_COMPLETION_TAG_TTL:-120}"',' cache_ts="${PM_COMPLETION_TAG_CACHE_TS:-0}"',' tag_values="${PM_COMPLETION_TAG_CACHE:-}"',' if [[ -z "$tag_values" || "$now" -eq 0 || $((now - cache_ts)) -ge "$ttl" ]]; then',' tag_values="$(pm completion-tags 2>/dev/null)"',' PM_COMPLETION_TAG_CACHE="$tag_values"',' PM_COMPLETION_TAG_CACHE_TS="$now"'," fi",' _pm_completion_add_matches "$tag_values"'," return 0"," fi"],"",' if [[ "$prev" == "--tag" && ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," COMPREPLY=()"," return 0"," fi","",' local cmd="" command_path="" word_index=1 word'," while (( word_index < cword )); do",' word="${COMP_WORDS[word_index]}"',' case "${word//_/-}" in',` ${vt}) (( word_index += 2 )); continue ;;`,` ${kt}|${St}) (( word_index++ )); continue ;;`," --) break ;;"," esac",' if [[ -z "$cmd" ]]; then',' cmd="$word"',' [[ "$cmd" == "ctx" ]] && cmd="context"',' command_path="$cmd"',` case "$cmd" in ${ht.join("|")}) ;; *) break ;; esac`," else",' case "$command_path $word" in',...J.map(A=>` "${A.canonical}") cmd="${A.alias}"; command_path="${A.canonical}" ;;`)," *) break ;;"," esac",` case "$command_path" in ${on.map(A=>`"${A}"`).join("|")}) ;; *) (( word_index++ )); break ;; esac`," fi"," (( word_index++ ))"," done",' case "$cmd" in',...Fp.flatMap(A=>[` ${A.alias})`,` ${_(A.flags)}`," return 0"," ;;"])," list)",` ${_(d)}`," ;;"," aggregate)",` ${_(wp)}`," ;;"," duplicates)",` ${_(Gp)}`," ;;"," create)",` ${_(m)}`," ;;"," copy)",` ${_(kp)}`," ;;"," focus)",` ${_(Sp)}`," ;;"," update)",` ${_(f)}`," if [[ $word_index -eq $cword ]]; then",` ${_(r.update)}`," fi"," ;;"," update-many)",` ${_(g)}`," ;;"," calendar|cal)",` ${_(k)}`," ;;"," context|ctx)",` ${_(b)}`," if [[ $word_index -eq $cword ]]; then",` ${_(r.context)}`," fi"," ;;"," ops)",` ${_(`${bo} ${r.ops}`)}`," ;;"," next)",` ${_(Dp)}`," ;;"," guide)",` ${_(`${qp} ${bt}`)}`," ;;"," search)",` ${_(y)}`," ;;"," reindex)",` ${_("--mode --progress --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," init)",` ${_(`${Wp} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," config)",` ${_("--criterion --clear-criteria --format --policy --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," extension)",` ${_(`${Be} ${Xp}`)}`," ;;"," package|packages)",` ${_(`${wt} ${Zp} ${Qp}`)}`," ;;"," comments)",` ${_("--add --body --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," notes)",` ${_("--add --add-json --stdin --file --edit --delete --expect-at --limit --since --event-type --include-meta --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," learnings)",` ${_("--add --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," files)",` ${_("discover lookup --add --add-glob --remove --migrate --list --apply --note --note-conflict --append-stable --validate-paths --full-history --scope --limit --offset --no-truncate --strict-read --explain --lines --decision-depth --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," docs)",` ${_("--add --add-glob --remove --migrate --note --note-conflict --validate-paths --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," append)",` ${_(vp)}`," ;;"," deps)",` ${_(jp)}`," ;;"," graph)",` ${_(`ancestors descendants predecessors successors paths impact analyze audit communities redundancy dominators slack centrality articulation plan index ${Up}`)}`," ;;"," test)",` ${_("--add --add-json --remove --remove-index --list --run --match --only-index --only-last --full-history --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --full-output --auto-pm-context --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-all)",` ${_("--status --limit --offset --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --full-output --auto-pm-context --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-runs)",` ${_("list status logs stop resume --status --limit --stream --tail --force --author --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," validate)",` ${_("--check-completeness --check-metadata --metadata-profile --check-resolution --check-lifecycle --check-stale-blockers --dependency-cycle-severity --parent-cycle-severity --check-files --scan-mode --include-pm-internals --verbose-file-lists --verbose-diagnostics --all-affected-ids --strict-exit --fail-on-warn --fix-hints --auto-fix --dry-run --fix-scope --prune-missing --check-history-drift --check-command-references --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," health)",` ${_(Bp)}`," ;;"," history)"," if [[ $word_index -eq $cword ]]; then",` ${_(`${xi} ${$p}`)}`," else",` ${_(xi)}`," fi"," ;;"," events)",` ${_(Np)}`," ;;"," history-author-acknowledge)",` ${_(`${Pp} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," get)",` ${_(Ep)}`," ;;"," schema)",' if [[ "$prev" == "policy-mode" ]]; then',` ${_("advise refuse")}`," return"," fi",` ${_(`${yt} --definition --policy --message --description --default-status --folder --alias --role --order --type --commands --cli-flag --required --required-on-create --no-allow-unset --required-types --infer --min-count --apply --to --migration-id --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," profile)",` ${_("list show apply lint agile ops research --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," plan)",` ${_(`${Jp} ${Kp}`)}`," ;;"," contracts)",` ${_(Vp)}`," ;;"," gc)",` ${_("--dry-run --scope --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," stats)",` ${_(Hp)}`," ;;"," close-task)",` ${_(nu)}`," ;;"," close)",` ${_(tu)}`,' if [[ "$cmd" == "close" && $word_index -eq $cword ]]; then',` ${_(r.close)}`," fi"," ;;"," close-many)",` ${_(Tp)}`," ;;"," release)",` ${_(ou)}`," ;;"," delete)",` ${_(eu)}`," ;;"," claim)",` ${_(ru)}`," ;;"," start-task)",` ${_(`${Ii} --takeover-stale`)}`," ;;"," pause-task)",` ${_(Ii)}`," ;;"," meet|event)",` ${_(Ap)}`," ;;"," remind)",` ${_(xp)}`," ;;"," completion)",` ${_(Yp)}`," ;;"," templates)",` ${_("save list show")}`," ;;"," *)",` ${_(bo)}`," ;;"," esac"," if [[ $word_index -eq $cword ]]; then",' case "$command_path" in',...Object.entries(r).filter(([A])=>["item","workspace","search"].includes(A.split(" ")[0])).map(([A,N])=>` "${A}") ${_(N)} ;;`)," esac"," fi",' if [[ "$cmd" == "comments" || "$cmd" == "notes" || "$cmd" == "learnings" ]]; then',` ${_("--text")}`," fi"," return 0","}","","complete -F _pm_completion pm"].join(`
78
- `)}function Ci(e){return e.replaceAll("\\","\\\\").replaceAll("'","\\'")}function su(e){return Ci(e.replace(/([^a-zA-Z0-9_:./\s-])/gu,"\\$1"))}var Sy=new Map([["calendar","Show deadline/reminder calendar views"],["schema","Inspect and manage runtime schema"],["profile","List, show, apply, and lint project profiles (archetype bundles)"],["plan","Agent-optimized Plan workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["start-task","Lifecycle alias to claim and set in-progress"]]);function Ay(){return[...yo,["ops","Workspace maintenance and diagnostics"]].filter(([e])=>e!=="help"&&!tn.has(e)).map(([e,t])=>{let n=Sy.get(e)??t;return`complete -c pm -n __pm_no_subcommand -a ${e.padEnd(16)} -d '${n}'`}).join(`
79
- `)}function We(e,t){let n=wo(t).map(r=>r.slice(2));if(e.length===0||n.length===0)return"";let o=[];for(let r of e){let i=ht.includes(r)||J.some(s=>s.alias===r)?"__pm_history_operation":"__fish_seen_subcommand_from";for(let s of n)o.push(`complete -c pm -n '${i} ${r}' -l '${Ci(s)}' -d 'Runtime schema field flag' -r`)}return`${o.join(`
74
+ `),a=r.length>t;return s.length>n&&(s=s.slice(0,n),a=!0),{excerpt:s.trimEnd(),truncated:a,lineCount:r.length}}async function fy(e,t,n){let o=t!=="brief",r=o?t==="deep"?"full":"excerpt":"none",i=[];for(let s of e.docs){let a=sy.resolve(n,s.path);if(!o){i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!0,line_count:null,content_mode:"none",content:null,truncated:!1});continue}try{let c=await iy(a,"utf8");if(t==="deep"){let l=bp(c).trimEnd();i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!0,line_count:l.length===0?0:l.split(`
75
+ `).length,content_mode:"full",content:l,truncated:!1})}else{let l=uy(c,120,12e3);i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!0,line_count:l.lineCount,content_mode:r,content:l.excerpt,truncated:l.truncated})}}catch(c){let l=Je(c);if(i.push({path:s.path,purpose:s.purpose,optional:s.optional===!0,exists:!1,line_count:null,content_mode:"none",content:null,truncated:!1}),!l)throw new p(`Failed to read guide document "${s.path}".`,u.GENERIC_FAILURE)}}return i}function _y(e){let t=gp().map(n=>({id:n.id,aliases:n.aliases,title:n.title,summary:n.summary,intent:n.intent,quick_commands:e==="brief"?n.commands.slice(0,3):n.commands.slice(0,6),docs:n.docs.map(o=>({path:o.path,purpose:o.purpose})),related:n.related}));return{output_default:"toon",mode:"index",depth:e,topics:t,suggested_next_steps:["pm guide <topic>","pm guide <topic> --depth standard","pm guide <topic> --depth deep --format markdown","pm guide <topic> --json"]}}function hy(e){let t=yp(e);if(t)return t;let n=_o().join(", ");throw new p(`Unknown guide topic "${e}". Available topics: ${n}. Use "pm guide --list" to browse.`,u.USAGE)}async function gy(e,t){let n=my(typeof e.depth=="string"?e.depth:void 0),o=e.list===!0,r=typeof e.topic=="string"?e.topic:void 0;if(o||!r)return _y(n);let i=hy(r),s=py(),a=await fy(i,n,s),c=a.filter(l=>!l.exists&&!l.optional).map(l=>`Missing required guide document: ${l.path}`);return{output_default:"toon",mode:"topic",depth:n,requested_topic:r,topic:i,docs:a,warnings:c}}function yy(e){return e.replaceAll("```","``\\`")}function by(e){if(e.mode==="index"){let n=["# pm guide","","Token-efficient local documentation index for agent and maintainer workflows.","","## Topics"];for(let o of e.topics)n.push(`- \`${o.id}\` - ${o.summary}`),e.depth!=="brief"&&(n.push(` - intent: ${o.intent}`),n.push(` - docs: ${o.docs.map(r=>`\`${r.path}\``).join(", ")}`));n.push("","## Next steps");for(let o of e.suggested_next_steps)n.push(`- \`${o}\``);return n.join(`
76
+ `)}let t=[`# pm guide ${e.topic.id}`,"",e.topic.summary,"","## Intent",e.topic.intent,"","## Key commands",...e.topic.commands.map(n=>`- \`${n}\``),"","## Workflow prompts"];for(let n of e.topic.workflows)t.push(`### ${n.name}`),t.push(`goal: ${n.goal}`),t.push(`prompt: ${n.prompt}`),t.push("commands:"),t.push(...n.commands.map(o=>`- \`${o}\``)),t.push("");t.push("## Documents");for(let n of e.docs){let o=n.exists?"available":n.optional?"missing (optional)":"missing (required)";t.push(`- \`${n.path}\` - ${n.purpose} (${o})`),n.exists&&n.content_mode!=="none"&&n.content&&(t.push(""),t.push(`### Excerpt: \`${n.path}\``),n.truncated&&t.push("_truncated for context efficiency_"),t.push("```markdown"),t.push(yy(n.content)),t.push("```"))}return e.topic.related.length>0&&(t.push("","## Related topics"),t.push(...e.topic.related.map(n=>`- \`${n}\``))),e.warnings.length>0&&(t.push("","## Warnings"),t.push(...e.warnings.map(n=>`- ${n}`))),t.join(`
77
+ `)}var wy=[...Pt],vy=[...Io],tn=new Set(Vi.filter(e=>e.hidden).map(e=>e.alias)),nn=Vc("full").filter(e=>!e.includes(" ")&&!tn.has(e)),wp=E(Pn),vp=E(Ha),kp=E(Qa),Sp=E(sc),ho=nr("restore",Ie("restore")),go=nr("history-attest",Ie("history-attest")),Ap=E(ac),xp=E(ec),Ip=E(tc),Ep=E(ic),Cp=E(uc),Rp=E(cc),Tp=E(lc),Op=E(Za),ht=[...new Set(Y.map(e=>e.canonical_argv[0]))],on=[...new Set(Y.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],ky=new Set(Ua.filter(e=>e.disposition==="package_owned").map(e=>So(e.command))),$p=Y.filter(e=>e.canonical_argv[0]==="history"),Fp=$p.map(e=>e.canonical_argv[1]).join(" ");function gt(e){let t=new Set((e.namespace_commands??[]).map(So)),n=Y.filter(o=>Wc(o.canonical)!=="internal"&&(!ky.has(o.alias)||t.has(o.alias)));return Object.fromEntries(on.map(o=>[o,[...new Set(n.filter(r=>r.canonical.startsWith(`${o} `)).map(r=>r.canonical_argv[o.split(" ").length]))].join(" ")]))}var Pp=$p.map(e=>({...e,flags:E(Ie(e.alias))})),xi=E(Ba),Np=E(Wa,!1),Lp=E(mc),Mp=E(dc),Dp=E(pc),jp=E(gc),Gp=E(_c),Up=E(oc),qp=E(hc),zp=E(fc),Hp=E(Nn),Bp=E(nc),Wp=E(rc),Vp=E(Ka),Kp=E(yc),Jp=E(Va),yt=`${dn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`,Yp="create show add-step update-step complete-step block-step reorder-step remove-step link unlink decision discovery validation resume approve materialize",Sy=E(bc),Xp=`${Sy} bash zsh fish`,bt=we(_o()),Be="init scaffold install uninstall list inventory explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",wt=`${Be} upgrade`,Zp=E(Ja),Qp=E(Ya),eu=E(Xa),Ii="--author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",tu="--dry-run --author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",nu=E(Ie("close")),ou=E(Ie("close-task")),ru=E(Ie("release")),iu=E(Ie("claim")),yo=[["workspace","Workspace initialization, customization, state and snapshots"],["init","Initialize pm storage for the current workspace"],["config","Read or update pm settings"],["package","Manage package lifecycle operations"],["packages","Alias for package"],["create","Create a new project management item"],["item","Manage item evidence, links, tests, and duplication"],["copy","Copy an existing item to a new ID"],["focus","Set/clear/show the session focused parent for new items"],["list","List active items with optional filters"],["aggregate","Aggregate grouped item counts and numeric stats for governance queries"],["duplicates","Find bounded duplicate clusters across lifecycle statuses"],["guide","Browse local progressive-disclosure guides"],["calendar","Show calendar views for deadlines and reminders"],["cal","Alias for calendar"],["context","Show a token-efficient project context snapshot"],["ctx","Alias for context"],["get","Show item details by ID"],["next","Recommend the next actionable (unblocked, ready) work item"],["search","Search items with keyword, semantic, or hybrid modes"],["reindex","Rebuild search artifacts"],["history","Show item history entries"],["history-compact","Compact history streams into a synthetic baseline + retained tail"],["history-redact","Redact and reseal item history."],["history-repair","Re-anchor a drifted history chain so pm health/validate report ok"],["schema","Manage custom item types and statuses in .agents/pm/schema/*.json"],["profile","List, show, apply, and lint project profiles (archetype schema/config/template/package bundles)"],["plan","Agent-optimized Plan item workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["activity","Show recent activity across items"],["restore","Restore an item to an earlier state"],["update","Update item fields and metadata"],["update-many","Bulk-update matched items with dry-run and rollback checkpoints"],["close","Close an item (reason requirement follows governance settings)"],["close-many","Bulk-close matched items with an optional shared reason and rollback checkpoint"],["delete","Delete an item and record the change"],["append","Append text to an item body"],["comments","List or add comments for an item"],["notes","List or add notes for an item"],["learnings","List or add learnings for an item"],["files","Manage linked files"],["docs","Manage linked docs"],["deps","Show dependency relationships for an item"],["graph","Bounded graph traversal, analytics, and governance-audit queries"],["test","Manage linked tests and optionally run them"],["test-all","Run linked tests across matching items"],["test-runs","Manage background linked-test runs"],["stats","Show project tracker statistics"],["health","Show project tracker health checks"],["validate","Run standalone validation checks"],["gc","Clean optional cache artifacts"],["contracts","Show machine-readable command and schema contracts"],["claim","Claim an item for active work"],["release","Release the active claim for an item"],["start-task","Lifecycle alias to claim and set in_progress"],["pause-task","Lifecycle alias to reopen and release claim"],["close-task","Lifecycle alias to close and release claim"],["meet","Shortcut to create a Meeting with scheduling defaults"],["event","Shortcut to create an Event with scheduling defaults"],["remind","Shortcut to create a Reminder from a point in time"],["templates","Manage reusable create templates"],["completion","Generate shell completion"],["help","Display help for a command"]],bo=za.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),vt=[...mn].join("|"),kt=[...mn].map(e=>`${e}=*`).join("|"),St=[...bo.split(" ").filter(e=>!mn.has(e)),"-h","-V"].join("|");function we(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}function Ay(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].join(" ")}function rn(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll("$","\\$").replaceAll("`","\\`")}function At(e,t){return Ay(e.length>0?e:t.item_types??wy)}function xt(e){return we(e.statuses??vy)}function $e(e,t){let n=[...e.split(/\s+/u).filter(o=>o.length>0),...t??[]];return we(n)}function wo(e){let t=(e??[]).map(n=>n.trim()).filter(n=>n.startsWith("--")&&n.length>2).map(n=>`--${n.slice(2).replaceAll("_","-")}`);return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function su(e,t,n){let o=e.toUpperCase(),r=`PM_COMPLETION_${o}_CACHE`,i=`PM_COMPLETION_${o}_CACHE_TS`,s=`PM_COMPLETION_${o}_TTL`,a=rn(n);return[`_pm_completion_${e}_choices() {`," local now ttl cache_ts resolved",' now="$(date +%s 2>/dev/null || echo 0)"',` ttl="\${${s}:-120}"`,` cache_ts="\${${i}:-0}"`,` if [[ -n "\${${r}:-}" && "$now" -ne 0 && $((now - cache_ts)) -lt "$ttl" ]]; then`,` printf '%s\\n' "$${r}"`," return 0"," fi",` resolved="$(pm ${t} 2>/dev/null)"`,' if [[ -z "$resolved" ]]; then',` resolved="${a}"`," fi",` ${r}="$resolved"`,` ${i}="$now"`,` printf '%s\\n' "$${r}"`,"}"]}function Ei(e=[],t=[],n=!1,o={}){let r=gt(o),i=nn.join(" "),s=e.length===0,a=At(e,o),c=xt(o),l=we(t),d=$e(wp,o.command_flags?.list),m=$e(Ep,o.command_flags?.create),f=$e(Rp,o.command_flags?.update),g=$e(Tp,o.command_flags?.["update-many"]),y=$e(Hp,o.command_flags?.search),k=$e(Mp,o.command_flags?.calendar),b=$e(Dp,o.command_flags?.context),v=n||t.length>0,_=A=>`_pm_completion_add_matches "${rn(A)}"`;return["# bash completion for pm",`# Source this file or add 'eval "$(pm completion bash)"' to ~/.bashrc`,"",...s?[...su("type","completion-types",a),""]:[],...su("status","completion-statuses",c),"","# Treat choices as data: no eval, compgen expansion, or filename globbing.","_pm_completion_add_matches() {"," local line value quoted parse_char parse_index"," local -a values"," while IFS= read -r line; do",' read -r -a values <<< "$line"',' for value in "${values[@]}"; do',' [[ "$value" == "$cur"* ]] || continue',' case "$quote_mode" in'," single)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("$quoted'")`," ;;"," double)"," quoted="," for (( parse_index=0; parse_index<${#value}; parse_index++ )); do",' parse_char="${value:parse_index:1}"',' case "$parse_char" in'," '\"'|'\\'|'$'|'`') quoted=\"${quoted}\\\\${parse_char}\" ;;",` '!') quoted="\${quoted}\\"'!'\\"" ;;`,' *) quoted="${quoted}${parse_char}" ;;'," esac"," done",' COMPREPLY+=("$quoted\\"")'," ;;"," *)",' case "$value" in'," *[!a-zA-Z0-9_.,:/@%+=-]*)"," quoted=${value//\\'/\\'\\\\\\'\\'}",` COMPREPLY+=("'$quoted'")`," ;;",' *) COMPREPLY+=("$value") ;;'," esac"," ;;"," esac"," done",' done <<< "$1"',"}","","_pm_completion() {"," local cur prev words cword raw_prefix quote_mode parse_char next_char parse_index quote_start escaped"," COMPREPLY=()",' raw_prefix="${COMP_WORDS[COMP_CWORD]}"'," _init_completion 2>/dev/null || {",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," cword=$COMP_CWORD"," }"," # Decode only the current Readline word. Never evaluate or expand it."," quote_mode=plain escaped=0 quote_start=0 cur="," for (( parse_index=0; parse_index<${#raw_prefix}; parse_index++ )); do",' parse_char="${raw_prefix:parse_index:1}"',' if (( escaped )); then cur="${cur}${parse_char}"; escaped=0; continue; fi',' case "$quote_mode" in'," single)",' if [[ "$parse_char" == "\'" ]]; then quote_mode=plain; else cur="${cur}${parse_char}"; fi'," ;;"," double)",' case "$parse_char" in',` '"') quote_mode=plain ;;`," '\\')",' next_char="${raw_prefix:parse_index+1:1}"',' case "$next_char" in'," '\"'|'\\'|'$'|'`') escaped=1 ;;",' *) cur="${cur}\\\\" ;;'," esac"," ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," *)",' case "$parse_char" in',` "'") quote_mode=single; quote_start=$parse_index ;;`,` '"') quote_mode=double; quote_start=$parse_index ;;`," '\\') escaped=1 ;;"," '`') return 0 ;;",' *) cur="${cur}${parse_char}" ;;'," esac"," ;;"," esac"," done"," # A mixed quoted segment has a different replacement span; keep it conservative.",' [[ "$quote_mode" != plain && $quote_start -ne 0 ]] && return 0',""," if [[ $cword -eq 1 ]]; then",` ${_(i)}`," return 0"," fi","",' if [[ "$prev" == "--type" ]]; then',s?' _pm_completion_add_matches "$(_pm_completion_type_choices)"':` ${_(a)}`," return 0"," fi","",' if [[ "$prev" == "--status" ]]; then',' _pm_completion_add_matches "$(_pm_completion_status_choices)"'," return 0"," fi","",...v?[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then',` ${_(l)}`," return 0"," fi"]:[' if [[ ( "$prev" == "--tag" || "$prev" == "--tags" ) && ! ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," local now ttl cache_ts tag_values",' now="$(date +%s 2>/dev/null || echo 0)"',' ttl="${PM_COMPLETION_TAG_TTL:-120}"',' cache_ts="${PM_COMPLETION_TAG_CACHE_TS:-0}"',' tag_values="${PM_COMPLETION_TAG_CACHE:-}"',' if [[ -z "$tag_values" || "$now" -eq 0 || $((now - cache_ts)) -ge "$ttl" ]]; then',' tag_values="$(pm completion-tags 2>/dev/null)"',' PM_COMPLETION_TAG_CACHE="$tag_values"',' PM_COMPLETION_TAG_CACHE_TS="$now"'," fi",' _pm_completion_add_matches "$tag_values"'," return 0"," fi"],"",' if [[ "$prev" == "--tag" && ( ( "${COMP_WORDS[1]}" == "package" || "${COMP_WORDS[1]}" == "packages" ) && "${COMP_WORDS[2]}" == "upgrade" ) ]]; then'," COMPREPLY=()"," return 0"," fi","",' local cmd="" command_path="" word_index=1 word'," while (( word_index < cword )); do",' word="${COMP_WORDS[word_index]}"',' case "${word//_/-}" in',` ${vt}) (( word_index += 2 )); continue ;;`,` ${kt}|${St}) (( word_index++ )); continue ;;`," --) break ;;"," esac",' if [[ -z "$cmd" ]]; then',' cmd="$word"',' [[ "$cmd" == "ctx" ]] && cmd="context"',' command_path="$cmd"',` case "$cmd" in ${ht.join("|")}) ;; *) break ;; esac`," else",' case "$command_path $word" in',...Y.map(A=>` "${A.canonical}") cmd="${A.alias}"; command_path="${A.canonical}" ;;`)," *) break ;;"," esac",` case "$command_path" in ${on.map(A=>`"${A}"`).join("|")}) ;; *) (( word_index++ )); break ;; esac`," fi"," (( word_index++ ))"," done",' case "$cmd" in',...Pp.flatMap(A=>[` ${A.alias})`,` ${_(A.flags)}`," return 0"," ;;"])," list)",` ${_(d)}`," ;;"," aggregate)",` ${_(vp)}`," ;;"," duplicates)",` ${_(Up)}`," ;;"," create)",` ${_(m)}`," ;;"," copy)",` ${_(Sp)}`," ;;"," focus)",` ${_(Ap)}`," ;;"," update)",` ${_(f)}`," if [[ $word_index -eq $cword ]]; then",` ${_(r.update)}`," fi"," ;;"," update-many)",` ${_(g)}`," ;;"," calendar|cal)",` ${_(k)}`," ;;"," context|ctx)",` ${_(b)}`," if [[ $word_index -eq $cword ]]; then",` ${_(r.context)}`," fi"," ;;"," ops)",` ${_(`${bo} ${r.ops}`)}`," ;;"," next)",` ${_(jp)}`," ;;"," guide)",` ${_(`${zp} ${bt}`)}`," ;;"," search)",` ${_(y)}`," ;;"," reindex)",` ${_("--mode --progress --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," init)",` ${_(`${Vp} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," config)",` ${_("--criterion --clear-criteria --format --policy --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," extension)",` ${_(`${Be} ${Zp}`)}`," ;;"," package|packages)",` ${_(`${wt} ${Qp} ${eu}`)}`," ;;"," comments)",` ${_("--add --body --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," notes)",` ${_("--add --add-json --stdin --file --edit --delete --expect-at --limit --since --event-type --include-meta --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," learnings)",` ${_("--add --stdin --file --edit --delete --expect-at --limit --full-history --if-absent --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," files)",` ${_("discover lookup --add --add-glob --remove --migrate --list --apply --note --note-conflict --append-stable --validate-paths --full-history --scope --limit --offset --no-truncate --strict-read --explain --lines --decision-depth --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," docs)",` ${_("--add --add-glob --remove --migrate --note --note-conflict --validate-paths --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," append)",` ${_(kp)}`," ;;"," deps)",` ${_(Gp)}`," ;;"," graph)",` ${_(`ancestors descendants predecessors successors paths impact analyze audit communities redundancy dominators slack centrality articulation plan index ${qp}`)}`," ;;"," test)",` ${_("--add --add-json --remove --remove-index --list --run --match --only-index --only-last --full-history --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --full-output --auto-pm-context --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-all)",` ${_("--status --limit --offset --background --timeout --progress --env-set --env-clear --shared-host-safe --pm-context --override-linked-pm-context --fail-on-context-mismatch --fail-on-skipped --fail-on-empty-test-run --require-assertions-for-pm --check-context --full-output --auto-pm-context --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," test-runs)",` ${_("list status logs stop resume --status --limit --stream --tail --force --author --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," validate)",` ${_("--check-completeness --check-metadata --metadata-profile --check-resolution --check-lifecycle --check-stale-blockers --dependency-cycle-severity --parent-cycle-severity --check-files --scan-mode --include-pm-internals --verbose-file-lists --verbose-diagnostics --all-affected-ids --strict-exit --fail-on-warn --fix-hints --auto-fix --dry-run --fix-scope --prune-missing --check-history-drift --check-command-references --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," health)",` ${_(Wp)}`," ;;"," history)"," if [[ $word_index -eq $cword ]]; then",` ${_(`${xi} ${Fp}`)}`," else",` ${_(xi)}`," fi"," ;;"," events)",` ${_(Lp)}`," ;;"," history-author-acknowledge)",` ${_(`${Np} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," get)",` ${_(Cp)}`," ;;"," schema)",' if [[ "$prev" == "policy-mode" ]]; then',` ${_("advise refuse")}`," return"," fi",` ${_(`${yt} --definition --policy --message --description --default-status --folder --alias --role --order --type --commands --cli-flag --required --required-on-create --no-allow-unset --required-types --infer --min-count --apply --to --migration-id --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)}`," ;;"," profile)",` ${_("list show apply lint agile ops research --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," plan)",` ${_(`${Yp} ${Jp}`)}`," ;;"," contracts)",` ${_(Kp)}`," ;;"," gc)",` ${_("--dry-run --scope --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")}`," ;;"," stats)",` ${_(Bp)}`," ;;"," close-task)",` ${_(ou)}`," ;;"," close)",` ${_(nu)}`,' if [[ "$cmd" == "close" && $word_index -eq $cword ]]; then',` ${_(r.close)}`," fi"," ;;"," close-many)",` ${_(Op)}`," ;;"," release)",` ${_(ru)}`," ;;"," delete)",` ${_(tu)}`," ;;"," claim)",` ${_(iu)}`," ;;"," start-task)",` ${_(`${Ii} --takeover-stale`)}`," ;;"," pause-task)",` ${_(Ii)}`," ;;"," meet|event)",` ${_(xp)}`," ;;"," remind)",` ${_(Ip)}`," ;;"," completion)",` ${_(Xp)}`," ;;"," templates)",` ${_("save list show")}`," ;;"," *)",` ${_(bo)}`," ;;"," esac"," if [[ $word_index -eq $cword ]]; then",' case "$command_path" in',...Object.entries(r).filter(([A])=>["item","workspace","search"].includes(A.split(" ")[0])).map(([A,N])=>` "${A}") ${_(N)} ;;`)," esac"," fi",' if [[ "$cmd" == "comments" || "$cmd" == "notes" || "$cmd" == "learnings" ]]; then',` ${_("--text")}`," fi"," return 0","}","","complete -F _pm_completion pm"].join(`
78
+ `)}function Ci(e){return e.replaceAll("\\","\\\\").replaceAll("'","\\'")}function au(e){return Ci(e.replace(/([^a-zA-Z0-9_:./\s-])/gu,"\\$1"))}var xy=new Map([["calendar","Show deadline/reminder calendar views"],["schema","Inspect and manage runtime schema"],["profile","List, show, apply, and lint project profiles (archetype bundles)"],["plan","Agent-optimized Plan workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["start-task","Lifecycle alias to claim and set in-progress"]]);function Iy(){return[...yo,["ops","Workspace maintenance and diagnostics"]].filter(([e])=>e!=="help"&&!tn.has(e)).map(([e,t])=>{let n=xy.get(e)??t;return`complete -c pm -n __pm_no_subcommand -a ${e.padEnd(16)} -d '${n}'`}).join(`
79
+ `)}function We(e,t){let n=wo(t).map(r=>r.slice(2));if(e.length===0||n.length===0)return"";let o=[];for(let r of e){let i=ht.includes(r)||Y.some(s=>s.alias===r)?"__pm_history_operation":"__fish_seen_subcommand_from";for(let s of n)o.push(`complete -c pm -n '${i} ${r}' -l '${Ci(s)}' -d 'Runtime schema field flag' -r`)}return`${o.join(`
80
80
  `)}
81
- `}function au(e,t,n){let o=e.toUpperCase(),r=Ci(n);return`
81
+ `}function cu(e,t,n){let o=e.toUpperCase(),r=Ci(n);return`
82
82
  function __pm_${e}_choices
83
83
  set -l now (date +%s 2>/dev/null)
84
84
  if test -z "$now"
@@ -103,7 +103,7 @@ function __pm_${e}_choices
103
103
  set -gx PM_COMPLETION_${o}_CACHE_TS $now
104
104
  printf '%s\\n' $resolved
105
105
  end
106
- `}function xy(e){return e?"":`
106
+ `}function Ey(e){return e?"":`
107
107
  function __pm_tag_choices
108
108
  set -l now (date +%s 2>/dev/null)
109
109
  if test -z "$now"
@@ -127,7 +127,7 @@ function __pm_tag_choices
127
127
  printf '%s
128
128
  ' $resolved
129
129
  end
130
- `}function Ri(e=[],t=[],n=!1,o={}){let r=gt(o),i=nn.filter(R=>R==="list"||R.startsWith("list-")),s=i.join(" "),a=nn.join(" "),c=e.length===0,l=At(e,o),d=xt(o),m=c?"(__pm_type_choices)":su(l),f="(__pm_status_choices)",g=bt,y=we(t),k=n||t.length>0,b=k?`'${su(y)}'`:"'(__pm_tag_choices)'",v=We(i,o.command_flags?.list),_=We(["create"],o.command_flags?.create),A=We(["update"],o.command_flags?.update),N=We(["update-many"],o.command_flags?.["update-many"]),O=We(["search"],o.command_flags?.search),B=We(["calendar","cal"],o.command_flags?.calendar),$=We(["context"],o.command_flags?.context);return`# Fish shell completion for pm
130
+ `}function Ri(e=[],t=[],n=!1,o={}){let r=gt(o),i=nn.filter(R=>R==="list"||R.startsWith("list-")),s=i.join(" "),a=nn.join(" "),c=e.length===0,l=At(e,o),d=xt(o),m=c?"(__pm_type_choices)":au(l),f="(__pm_status_choices)",g=bt,y=we(t),k=n||t.length>0,b=k?`'${au(y)}'`:"'(__pm_tag_choices)'",v=We(i,o.command_flags?.list),_=We(["create"],o.command_flags?.create),A=We(["update"],o.command_flags?.update),N=We(["update-many"],o.command_flags?.["update-many"]),O=We(["search"],o.command_flags?.search),B=We(["calendar","cal"],o.command_flags?.calendar),$=We(["context"],o.command_flags?.context);return`# Fish shell completion for pm
131
131
  # Save to ~/.config/fish/completions/pm.fish
132
132
  # or run: pm completion fish > ~/.config/fish/completions/pm.fish
133
133
 
@@ -157,12 +157,12 @@ complete -c pm -s h -l help -d 'Display help'
157
157
  function __pm_no_subcommand
158
158
  not __fish_seen_subcommand_from ${a}
159
159
  end
160
- ${xy(k)}
161
- ${c?au("type","completion-types",l):""}
162
- ${au("status","completion-statuses",d)}
160
+ ${Ey(k)}
161
+ ${c?cu("type","completion-types",l):""}
162
+ ${cu("status","completion-statuses",d)}
163
163
 
164
164
  # Subcommands
165
- ${Ay()}
165
+ ${Iy()}
166
166
 
167
167
  # list* flags
168
168
  for list_cmd in ${s}
@@ -636,7 +636,7 @@ end
636
636
  function __pm_history_operation
637
637
  set -l tokens (__pm_history_tokens)
638
638
  switch (string join ' ' -- $tokens)
639
- ${[...J].sort((R,ie)=>ie.canonical_argv.length-R.canonical_argv.length).map(R=>` case '${R.canonical}' '${R.canonical} *'
639
+ ${[...Y].sort((R,ie)=>ie.canonical_argv.length-R.canonical_argv.length).map(R=>` case '${R.canonical}' '${R.canonical} *'
640
640
  contains -- '${R.alias}' $argv
641
641
  return`).join(`
642
642
  `)}
@@ -1148,8 +1148,8 @@ for package_cmd in package packages
1148
1148
  end`}function Ti(e){return e.replace(/([^a-zA-Z0-9_./\s-])/gu,"\\$1").replaceAll("'","'\\''")}function sn(e){let t=wo(e);return t.length===0?"":`${t.map(n=>` '${Ti(n)}[Runtime schema field flag]:value' \\`).join(`
1149
1149
  `)}
1150
1150
  `}function It(e,t={}){let n=t.trailingContinuation??!0,o=e.length-1;return e.map((r,i)=>` ${r}${n||i!==o?" \\":""}`).join(`
1151
- `)}function Iy(){return[...yo,["ops","Workspace maintenance and diagnostics"]].filter(([e])=>!tn.has(e)).map(([e,t])=>` '${e}:${t}'`).join(`
1152
- `)}function cu(e){let t=["reviewer-missing[Select only items missing reviewer]","risk-missing[Select only items missing risk]","confidence-missing[Select only items missing confidence]","sprint-missing[Select only items missing sprint]","release-missing[Select only items missing release]"],n=e.includeContentMissingAliases===!0?["files-missing[Alias for --no-files]","docs-missing[Alias for --no-docs]"]:[],o=[["has-notes[Select only items that have notes]","no-notes[Select only items with no notes]"],["has-learnings[Select only items that have learnings]","no-learnings[Select only items with no learnings]"],["has-files[Select only items that have linked files]","no-files[Select only items with no linked files]"],["has-docs[Select only items that have linked docs]","no-docs[Select only items with no linked docs]"],["has-tests[Select only items that have linked tests]","no-tests[Select only items with no linked tests]"],["has-comments[Select only items that have comments]","no-comments[Select only items with no comments]"],["has-deps[Select only items that have dependencies]","no-deps[Select only items with no dependencies]"],["has-body[Select only items with non-empty body]","empty-body[Select only items with empty body]"],["has-linked-command[Select only items that have a linked command]","no-linked-command[Select only items with no linked command]"]];return It([...[...t,...n].map(r=>`'--${e.missingPrefix}${r}'`),...o.flatMap(([r,i])=>[`'--${e.pairedPrefix}${r}'`,`'--${e.pairedPrefix}${i}'`])])}var Ey=["'--comment[Comment seed author=<value>,created_at=<iso|now>,text=<value>]:comment'","'--note[Note seed author=<value>,created_at=<iso|now>,text=<value>]:note'","'--learning[Learning seed author=<value>,created_at=<iso|now>,text=<value>]:learning'","'--file[Linked file path=<value>,scope=<project|global>,note=<text>]:file'","'--test[Linked test command=<value>,path=<value>,scope=<project|global>]:test'","'--doc[Linked doc path=<value>,scope=<project|global>,note=<text>]:doc'","'--reminder[Reminder entry at=<iso|relative>|date=<iso|relative>,text=<text>|title=<text>]:reminder'","'--event[Event entry start=<iso|relative>,end=<iso|relative>,recur_*]:event'","'--type-option[Type option key=value or key=<name>,value=<value>]:type_option'","'--unset[Clear scalar fields by name (repeatable or csv)]:field'","'--replace-files[Atomically replace linked files with provided --file values]'","'--replace-docs[Atomically replace linked docs with provided --doc values]'","'--clear-deps[Clear dependency entries]'","'--clear-comments[Clear comments]'","'--clear-notes[Clear notes]'","'--clear-learnings[Clear learnings]'","'--clear-files[Clear linked files]'","'--clear-tests[Clear linked tests]'","'--clear-docs[Clear linked docs]'","'--clear-reminders[Clear reminders]'","'--clear-events[Clear events]'","'--clear-type-options[Clear type options]'"];function lu(e){return It([...e==="reminder"?["'--at[Reminder time (default +1d)]:at'","'--text[Reminder text (defaults to title)]:text'"]:["'--start[Start time (ISO, now, or relative)]:start'","'--duration[Duration from start (default 1h)]:duration'","'--end[End time (overrides --duration)]:end'","'--location[Location]:location'","'--timezone[IANA timezone]:timezone'","'--all-day[Mark as an all-day event]'"],"'--parent[Parent item id]:parent'","'--allow-missing-parent[Permit a parent id that does not exist yet]'","'--tags[Comma-separated tags]:tags'","'(-p --priority)'{-p,--priority}'[Priority (0-4)]:(0 1 2 3 4)'","'(-b --body)'{-b,--body}'[Item body]:body'","'(-d --description)'{-d,--description}'[Short description]:description'","'--author[Mutation author]:author'","'--message[History message]:message'","'--json[Output JSON]'","'--quiet[Suppress stdout]'"],{trailingContinuation:!1})}function du(e,t,n,o){return It([`'--filter-status[Filter by status before ${e}]:(${t})'`,`'--filter-type[Filter by type before ${e}]:(${n})'`,`'--filter-tag[Filter by tag before ${e}]:(${o})'`,`'--filter-priority[Filter by priority before ${e}]:(0 1 2 3 4)'`,"'--filter-deadline-before[Filter by deadline upper bound]:deadline'","'--filter-deadline-after[Filter by deadline lower bound]:deadline'","'--filter-updated-after[Filter by updated_at lower bound (ISO/relative)]:timestamp'","'--filter-updated-before[Filter by updated_at upper bound (ISO/relative)]:timestamp'","'--filter-created-after[Filter by created_at lower bound (ISO/relative)]:timestamp'","'--filter-created-before[Filter by created_at upper bound (ISO/relative)]:timestamp'",`'--filter-assignee[Filter by assignee before ${e}]:assignee'`,"'--filter-assignee-filter[Filter assignee presence]:(assigned unassigned)'","'--filter-parent[Filter by parent item ID]:parent'","'--filter-sprint[Filter by sprint]:sprint'","'--filter-release[Filter by release]:release'"])}function mu(e,t,n){let o=e.toUpperCase(),r=`PM_COMPLETION_${o}_CACHE`,i=`PM_COMPLETION_${o}_CACHE_TS`,s=`PM_COMPLETION_${o}_TTL`,a=rn(n);return`
1151
+ `)}function Cy(){return[...yo,["ops","Workspace maintenance and diagnostics"]].filter(([e])=>!tn.has(e)).map(([e,t])=>` '${e}:${t}'`).join(`
1152
+ `)}function lu(e){let t=["reviewer-missing[Select only items missing reviewer]","risk-missing[Select only items missing risk]","confidence-missing[Select only items missing confidence]","sprint-missing[Select only items missing sprint]","release-missing[Select only items missing release]"],n=e.includeContentMissingAliases===!0?["files-missing[Alias for --no-files]","docs-missing[Alias for --no-docs]"]:[],o=[["has-notes[Select only items that have notes]","no-notes[Select only items with no notes]"],["has-learnings[Select only items that have learnings]","no-learnings[Select only items with no learnings]"],["has-files[Select only items that have linked files]","no-files[Select only items with no linked files]"],["has-docs[Select only items that have linked docs]","no-docs[Select only items with no linked docs]"],["has-tests[Select only items that have linked tests]","no-tests[Select only items with no linked tests]"],["has-comments[Select only items that have comments]","no-comments[Select only items with no comments]"],["has-deps[Select only items that have dependencies]","no-deps[Select only items with no dependencies]"],["has-body[Select only items with non-empty body]","empty-body[Select only items with empty body]"],["has-linked-command[Select only items that have a linked command]","no-linked-command[Select only items with no linked command]"]];return It([...[...t,...n].map(r=>`'--${e.missingPrefix}${r}'`),...o.flatMap(([r,i])=>[`'--${e.pairedPrefix}${r}'`,`'--${e.pairedPrefix}${i}'`])])}var Ry=["'--comment[Comment seed author=<value>,created_at=<iso|now>,text=<value>]:comment'","'--note[Note seed author=<value>,created_at=<iso|now>,text=<value>]:note'","'--learning[Learning seed author=<value>,created_at=<iso|now>,text=<value>]:learning'","'--file[Linked file path=<value>,scope=<project|global>,note=<text>]:file'","'--test[Linked test command=<value>,path=<value>,scope=<project|global>]:test'","'--doc[Linked doc path=<value>,scope=<project|global>,note=<text>]:doc'","'--reminder[Reminder entry at=<iso|relative>|date=<iso|relative>,text=<text>|title=<text>]:reminder'","'--event[Event entry start=<iso|relative>,end=<iso|relative>,recur_*]:event'","'--type-option[Type option key=value or key=<name>,value=<value>]:type_option'","'--unset[Clear scalar fields by name (repeatable or csv)]:field'","'--replace-files[Atomically replace linked files with provided --file values]'","'--replace-docs[Atomically replace linked docs with provided --doc values]'","'--clear-deps[Clear dependency entries]'","'--clear-comments[Clear comments]'","'--clear-notes[Clear notes]'","'--clear-learnings[Clear learnings]'","'--clear-files[Clear linked files]'","'--clear-tests[Clear linked tests]'","'--clear-docs[Clear linked docs]'","'--clear-reminders[Clear reminders]'","'--clear-events[Clear events]'","'--clear-type-options[Clear type options]'"];function du(e){return It([...e==="reminder"?["'--at[Reminder time (default +1d)]:at'","'--text[Reminder text (defaults to title)]:text'"]:["'--start[Start time (ISO, now, or relative)]:start'","'--duration[Duration from start (default 1h)]:duration'","'--end[End time (overrides --duration)]:end'","'--location[Location]:location'","'--timezone[IANA timezone]:timezone'","'--all-day[Mark as an all-day event]'"],"'--parent[Parent item id]:parent'","'--allow-missing-parent[Permit a parent id that does not exist yet]'","'--tags[Comma-separated tags]:tags'","'(-p --priority)'{-p,--priority}'[Priority (0-4)]:(0 1 2 3 4)'","'(-b --body)'{-b,--body}'[Item body]:body'","'(-d --description)'{-d,--description}'[Short description]:description'","'--author[Mutation author]:author'","'--message[History message]:message'","'--json[Output JSON]'","'--quiet[Suppress stdout]'"],{trailingContinuation:!1})}function mu(e,t,n,o){return It([`'--filter-status[Filter by status before ${e}]:(${t})'`,`'--filter-type[Filter by type before ${e}]:(${n})'`,`'--filter-tag[Filter by tag before ${e}]:(${o})'`,`'--filter-priority[Filter by priority before ${e}]:(0 1 2 3 4)'`,"'--filter-deadline-before[Filter by deadline upper bound]:deadline'","'--filter-deadline-after[Filter by deadline lower bound]:deadline'","'--filter-updated-after[Filter by updated_at lower bound (ISO/relative)]:timestamp'","'--filter-updated-before[Filter by updated_at upper bound (ISO/relative)]:timestamp'","'--filter-created-after[Filter by created_at lower bound (ISO/relative)]:timestamp'","'--filter-created-before[Filter by created_at upper bound (ISO/relative)]:timestamp'",`'--filter-assignee[Filter by assignee before ${e}]:assignee'`,"'--filter-assignee-filter[Filter assignee presence]:(assigned unassigned)'","'--filter-parent[Filter by parent item ID]:parent'","'--filter-sprint[Filter by sprint]:sprint'","'--filter-release[Filter by release]:release'"])}function pu(e,t,n){let o=e.toUpperCase(),r=`PM_COMPLETION_${o}_CACHE`,i=`PM_COMPLETION_${o}_CACHE_TS`,s=`PM_COMPLETION_${o}_TTL`,a=rn(n);return`
1153
1153
  _pm_${e}_choices() {
1154
1154
  local now ttl cache_ts resolved
1155
1155
  now=\${EPOCHSECONDS:-0}
@@ -1167,7 +1167,7 @@ _pm_${e}_choices() {
1167
1167
  ${i}="$now"
1168
1168
  print -r -- "$${r}"
1169
1169
  }
1170
- `}function Oi(e=[],t=[],n=!1,o={}){let r=gt(o),i=e.length===0,s=At(e,o),a=xt(o),c=i?'${(f)"$(_pm_type_choices)"}':Ti(s),l='${(f)"$(_pm_status_choices)"}',d=bt,m=we(t),f=n||t.length>0,g=f?Ti(m):'${(f)"$(_pm_tag_choices)"}',y=sn(o.command_flags?.list),k=sn(o.command_flags?.create),b=sn(o.command_flags?.search),v=sn(o.command_flags?.calendar),_=sn(o.command_flags?.context),A=cu({missingPrefix:"filter-",pairedPrefix:"",includeContentMissingAliases:!0}),N=cu({missingPrefix:"filter-",pairedPrefix:"filter-"}),O=It(Ey),B=f?"":`
1170
+ `}function Oi(e=[],t=[],n=!1,o={}){let r=gt(o),i=e.length===0,s=At(e,o),a=xt(o),c=i?'${(f)"$(_pm_type_choices)"}':Ti(s),l='${(f)"$(_pm_status_choices)"}',d=bt,m=we(t),f=n||t.length>0,g=f?Ti(m):'${(f)"$(_pm_tag_choices)"}',y=sn(o.command_flags?.list),k=sn(o.command_flags?.create),b=sn(o.command_flags?.search),v=sn(o.command_flags?.calendar),_=sn(o.command_flags?.context),A=lu({missingPrefix:"filter-",pairedPrefix:"",includeContentMissingAliases:!0}),N=lu({missingPrefix:"filter-",pairedPrefix:"filter-"}),O=It(Ry),B=f?"":`
1171
1171
  _pm_tag_choices() {
1172
1172
  local now ttl cache_ts
1173
1173
  now=\${EPOCHSECONDS:-0}
@@ -1188,13 +1188,13 @@ _pm_tag_choices() {
1188
1188
  _pm_commands() {
1189
1189
  local -a commands
1190
1190
  commands=(
1191
- ${Iy()}
1191
+ ${Cy()}
1192
1192
  )
1193
1193
  _describe 'command' commands
1194
1194
  }
1195
1195
  ${B}
1196
- ${i?mu("type","completion-types",s):""}
1197
- ${mu("status","completion-statuses",a)}
1196
+ ${i?pu("type","completion-types",s):""}
1197
+ ${pu("status","completion-statuses",a)}
1198
1198
 
1199
1199
  _pm() {
1200
1200
  local context state line
@@ -1214,7 +1214,7 @@ _pm() {
1214
1214
  namespace_noun="$word"
1215
1215
  else
1216
1216
  case "$namespace_noun $word" in
1217
- ${J.map($=>` "${$.canonical}") namespace_noun="${$.canonical}"; operation_path="$namespace_noun"; operation_index=$word_index ;;`).join(`
1217
+ ${Y.map($=>` "${$.canonical}") namespace_noun="${$.canonical}"; operation_path="$namespace_noun"; operation_index=$word_index ;;`).join(`
1218
1218
  `)}
1219
1219
  *) break ;;
1220
1220
  esac
@@ -1234,7 +1234,7 @@ ${Object.entries(r).map(([$,R])=>` "${$}") history_commands=(${R}) ;;`).joi
1234
1234
  fi
1235
1235
  if (( operation_index > 0 )); then
1236
1236
  case "$operation_path" in
1237
- ${J.map($=>` "${$.canonical}") words=("$words[1]" "${$.alias}" "\${words[@]:$operation_index}"); (( CURRENT -= operation_index - 2 )) ;;`).join(`
1237
+ ${Y.map($=>` "${$.canonical}") words=("$words[1]" "${$.alias}" "\${words[@]:$operation_index}"); (( CURRENT -= operation_index - 2 )) ;;`).join(`
1238
1238
  `)}
1239
1239
  esac
1240
1240
  fi
@@ -1385,11 +1385,11 @@ ${k} '--json[Output JSON]' \\
1385
1385
  ;;
1386
1386
  meet|event)
1387
1387
  _arguments \\
1388
- ${lu("event")}
1388
+ ${du("event")}
1389
1389
  ;;
1390
1390
  remind)
1391
1391
  _arguments \\
1392
- ${lu("reminder")}
1392
+ ${du("reminder")}
1393
1393
  ;;
1394
1394
  update)
1395
1395
  _arguments \\
@@ -1417,7 +1417,7 @@ ${O}
1417
1417
  ;;
1418
1418
  update-many)
1419
1419
  _arguments \\
1420
- ${du("applying updates",l,c,g)}
1420
+ ${mu("applying updates",l,c,g)}
1421
1421
  '--filter-ac-missing[Select only items missing acceptance_criteria]' \\
1422
1422
  '--filter-estimates-missing[Select only items missing estimated_minutes]' \\
1423
1423
  '--filter-resolution-missing[Select only terminal items missing resolution]' \\
@@ -1482,7 +1482,7 @@ ${O}
1482
1482
  ;;
1483
1483
  close-many)
1484
1484
  _arguments \\
1485
- ${du("closing",l,c,g)}
1485
+ ${mu("closing",l,c,g)}
1486
1486
  ${N}
1487
1487
  '--ids[Explicit comma-separated ID allowlist]:ids' \\
1488
1488
  '--limit[Limit matched item count]:number' \\
@@ -2281,9 +2281,9 @@ ${It(ho.map($=>`'${$.flag}[${$.description}]${$.takes_value?":value":""}'`),{tra
2281
2281
  esac
2282
2282
  }
2283
2283
 
2284
- compdef _pm pm`}var pu=["bash","zsh","fish"],Cy={bash:'Add to ~/.bashrc or ~/.bash_profile: eval "$(pm completion bash)"',zsh:'Add to ~/.zshrc: eval "$(pm completion zsh)"',fish:"Run: pm completion fish > ~/.config/fish/completions/pm.fish"};function Ry(e,t=[],n=[],o=!1,r={}){let i=e.trim().toLowerCase();if(!pu.includes(i))throw new p(`Unknown shell: "${e}". Supported shells: ${pu.join(", ")}.`,u.USAGE);let s=i,a;return s==="bash"?a=Ei(t,n,o,r):s==="zsh"?a=Oi(t,n,o,r):a=Ri(t,n,o,r),{shell:s,script:a,setup_hint:Cy[s]}}import Ty from"node:fs/promises";import an from"node:path";var $i="index/manifest.json",Fi="search/embeddings.jsonl",Oy="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function $y(e){return e.progress===!0||process.stderr.isTTY===!0}function D(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
2285
- `)}catch{}}function Fy(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new p("Reindex mode must be one of keyword|semantic|hybrid",u.USAGE)}async function Py(e,t,n,o){let r=[];return{candidates:await _a(e,t,n,r,o),warnings:r}}async function Ni(e,t,n,o,r){let i=pe(T()),s=[];for(let a of t)if(!(r&&!r.has(a.metadata.id))){if(typeof a.body=="string"){s.push({metadata:a.metadata,body:a.body});continue}try{let c=await Ty.readFile(a.item_path,"utf8"),l=bn(c,{format:a.item_format,schema:n,extensionFieldNames:i,onWarning:d=>o.push(d)});s.push({metadata:a.metadata,body:l.body})}catch{o.push(`item_list_item_read_failed:${an.relative(e,a.item_path)}`),s.push({metadata:a.metadata,body:""})}}return s}function Ny(e,t,n){let o=e.metadata;return{id:o.id,mode:t,updated_at:o.updated_at,corpus:ba(e,{fields:n})}}var Et=ms;function Ly(e){let t=T(),n=Et(e.search?.provider);if(!n)return null;let o=Xs(t,n);if(!o)return null;let r=o.runtime_definition??o.definition,i=Et(r.name)??Et(o.definition.name);if(!i)return null;let s=r.embedBatch,a=r.embed_batch,c=r.embed,l=typeof s=="function"?s:typeof a=="function"?a:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:i,embedBatch:l,embed:d}}function My(e){let t=T(),n=Et(e.vector_store?.adapter);if(!n)return null;let o=Zs(t,n);if(!o)return null;let r=o.runtime_definition??o.definition,i=Et(r.name)??Et(o.definition.name);if(!i)return null;let s=r.upsert,a=r.delete;return{adapterName:i,...typeof s=="function"?{upsert:s}:{},...typeof a=="function"?{delete:a}:{}}}function Pi(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new p(`Invalid vector returned by ${t}`,u.GENERIC_FAILURE);return e}async function Dy(e,t,n){let o=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let i=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:o}));if(!Array.isArray(i))throw new p(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,u.GENERIC_FAILURE);return i.map((s,a)=>Pi(s,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new p(`Extension search provider "${e.name}" does not implement embed/embedBatch`,u.GENERIC_FAILURE);let r=[];for(let[i,s]of n.entries()){let a=await Promise.resolve(e.embed({input:s,settings:t,model:o}));r.push(Pi(a,`extension search provider "${e.name}" embed output at index ${i}`))}return r}function uu(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function fu(e,t,n){let o=n?zt(n.name,uu(e)):t?zt(t.name,t.model):null;if(!o)throw new p("No embedding identity available for semantic reindex mode",u.USAGE);return o}function jy(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,o)=>n.localeCompare(o))}async function _u(e,t,n,o,r,i,s,a){let c=o?.name??n?.name,l=wa(c,e.search.embedding_corpus_max_characters).maxCharacters,d=Jo(e),m=r.map(y=>va(y,{providerName:c,maxCharacters:l,fields:d})),f=[],g=null;if(o)try{f=await Dy(o,e,m),g=zt(o.name,uu(e))}catch(y){if(!n)throw new p(`Extension search provider "${o.name}" failed to generate embeddings: ${y instanceof Error?y.message:String(y)}`,u.GENERIC_FAILURE);i.push(`Extension search provider "${o.name}" failed; falling back to built-in provider (${y instanceof Error?y.message:String(y)})`)}if(f.length===0){if(!n)throw new p(`No embedding executor available for reindex mode '${t}'`,u.USAGE);let y=await ka(n,e,m,{onProgress:k=>{k.phase==="complete"&&(s.batches_completed=k.batch_index),D(a,`embedding_batch_${k.phase} batch=${k.batch_index}/${k.batch_total} size=${k.batch_size} completed_inputs=${k.completed_inputs}/${k.total_inputs}`)}});i.push(...y.warnings),s.batching=y.receipt,f=y.vectors,g=zt(n.name,n.model)}if(D(a,`embedding_complete vectors=${f.length}`),f.length!==r.length)throw new p(`Embedding output size mismatch (expected ${r.length}, received ${f.length})`,u.GENERIC_FAILURE);if(!g)throw new p(`No embedding identity available for reindex mode '${t}'`,u.USAGE);return{vectors:f,embeddingIdentity:g}}async function Gy(e,t,n,o,r,i){let s=Object.keys(n);if(t){if(s.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:s.sort((a,c)=>a.localeCompare(c)),settings:o}))}catch(a){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,u.GENERIC_FAILURE)}else s.length>0&&r.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${s.length}`);if(!e)return}e&&await Ia(e,s,{},i)}async function hu(e,t,n,o,r){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:o}))}catch(i){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${i instanceof Error?i.message:String(i)}`,u.GENERIC_FAILURE)}else r.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await xa(e,n)}}function Uy(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function qy(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(o=>({id:o.metadata.id,type:o.metadata.type,status:o.metadata.status,priority:o.metadata.priority,updated_at:o.metadata.updated_at}))}}function zy(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Ko(e.settings);if(!t.active&&!e.extensionEmbedding)throw new p(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,u.USAGE);let n=Sa(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new p(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,u.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function Hy(e){let t=F(e.settings,T()),n=await Py(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(o=>({metadata:o.metadata,body:typeof o.body=="string"?o.body:""}))}}async function By(e){let t=await Xo(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return fu(e.settings,Ko(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&$n(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(Oy))}async function Wy(e){let t=await Xo(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=fu(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),o=new Set(e.metadataDocuments.map(l=>l.metadata.id)),r=jy(t.entries,o),i=$n(t.embedding,n);e.forceFullSemantic&&!i&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let s=e.forceFullSemantic||i?e.metadataDocuments:e.metadataDocuments.filter(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),a=new Set(s.map(l=>l.metadata.id)),c=a.size>0?await Ni(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:r,resetRequired:i,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function Vy(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await Ni(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,D(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let o=await _u(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...o,staleDocuments:n,vectorDimension:Yo(o.vectors,"Reindex embeddings")}}async function Ky(e){let t=await _u(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,o=t.embeddingIdentity,r=Yo(n,"Reindex embeddings");if(!(!e.resetRequired&&($n(e.ledgerEmbedding,o)||Ca(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:o,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let s=await Vy(e);return n=s.vectors,o=s.embeddingIdentity,r=s.vectorDimension,{vectors:n,embeddingIdentity:o,staleDocuments:s.staleDocuments,vectorDimension:r,resetRequired:!0}}async function Jy(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(D(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new p(`Extension vector adapter "${t}" does not support upserting vectors.`,u.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,D(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof p)throw t;if(!e.activeVectorStore)throw new p(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,u.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),D(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){D(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Aa(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,D(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new p(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,u.USAGE)}function Yy(e,t){return e.map((n,o)=>({id:n.metadata.id,vector:Pi(t[o],`reindex embeddings output at index ${o}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function Xy(e){D(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await Ky({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(D(e.progressEnabled,"vector_reset_start"),await Gy(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),D(e.progressEnabled,"vector_reset_complete")):await hu(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=Yy(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await Jy({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Ea(t.embeddingIdentity,t.vectorDimension)}}async function Zy(e){let t=await Wy(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(i=>[i.metadata.id,i.metadata.updated_at]));if(D(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return D(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await hu(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let o=await Xy({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let r=new Map(o.staleDocuments.map(i=>[i.metadata.id,i]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(i=>r.get(i.metadata.id)??i),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:o.embeddingMetadata}}async function Qy(e){let t=an.join(e.pmRoot,$i),n=an.join(e.pmRoot,Fi),o=Jo(e.settings),r=e.documentsForKeywordArtifacts.map(s=>JSON.stringify(Ny(s,e.mode,o))).join(`
2284
+ compdef _pm pm`}var uu=["bash","zsh","fish"],Ty={bash:'Add to ~/.bashrc or ~/.bash_profile: eval "$(pm completion bash)"',zsh:'Add to ~/.zshrc: eval "$(pm completion zsh)"',fish:"Run: pm completion fish > ~/.config/fish/completions/pm.fish"};function Oy(e,t=[],n=[],o=!1,r={}){let i=e.trim().toLowerCase();if(!uu.includes(i))throw new p(`Unknown shell: "${e}". Supported shells: ${uu.join(", ")}.`,u.USAGE);let s=i,a;return s==="bash"?a=Ei(t,n,o,r):s==="zsh"?a=Oi(t,n,o,r):a=Ri(t,n,o,r),{shell:s,script:a,setup_hint:Ty[s]}}import $y from"node:fs/promises";import an from"node:path";var $i="index/manifest.json",Fi="search/embeddings.jsonl",Fy="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function Py(e){return e.progress===!0||process.stderr.isTTY===!0}function D(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
2285
+ `)}catch{}}function Ny(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new p("Reindex mode must be one of keyword|semantic|hybrid",u.USAGE)}async function Ly(e,t,n,o){let r=[];return{candidates:await ga(e,t,n,r,o),warnings:r}}async function Ni(e,t,n,o,r){let i=ue(T()),s=[];for(let a of t)if(!(r&&!r.has(a.metadata.id))){if(typeof a.body=="string"){s.push({metadata:a.metadata,body:a.body});continue}try{let c=await $y.readFile(a.item_path,"utf8"),l=wn(c,{format:a.item_format,schema:n,extensionFieldNames:i,onWarning:d=>o.push(d)});s.push({metadata:a.metadata,body:l.body})}catch{o.push(`item_list_item_read_failed:${an.relative(e,a.item_path)}`),s.push({metadata:a.metadata,body:""})}}return s}function My(e,t,n){let o=e.metadata;return{id:o.id,mode:t,updated_at:o.updated_at,corpus:va(e,{fields:n})}}var Et=ms;function Dy(e){let t=T(),n=Et(e.search?.provider);if(!n)return null;let o=Qs(t,n);if(!o)return null;let r=o.runtime_definition??o.definition,i=Et(r.name)??Et(o.definition.name);if(!i)return null;let s=r.embedBatch,a=r.embed_batch,c=r.embed,l=typeof s=="function"?s:typeof a=="function"?a:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:i,embedBatch:l,embed:d}}function jy(e){let t=T(),n=Et(e.vector_store?.adapter);if(!n)return null;let o=ea(t,n);if(!o)return null;let r=o.runtime_definition??o.definition,i=Et(r.name)??Et(o.definition.name);if(!i)return null;let s=r.upsert,a=r.delete;return{adapterName:i,...typeof s=="function"?{upsert:s}:{},...typeof a=="function"?{delete:a}:{}}}function Pi(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new p(`Invalid vector returned by ${t}`,u.GENERIC_FAILURE);return e}async function Gy(e,t,n){let o=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let i=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:o}));if(!Array.isArray(i))throw new p(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,u.GENERIC_FAILURE);return i.map((s,a)=>Pi(s,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new p(`Extension search provider "${e.name}" does not implement embed/embedBatch`,u.GENERIC_FAILURE);let r=[];for(let[i,s]of n.entries()){let a=await Promise.resolve(e.embed({input:s,settings:t,model:o}));r.push(Pi(a,`extension search provider "${e.name}" embed output at index ${i}`))}return r}function fu(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function _u(e,t,n){let o=n?zt(n.name,fu(e)):t?zt(t.name,t.model):null;if(!o)throw new p("No embedding identity available for semantic reindex mode",u.USAGE);return o}function Uy(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,o)=>n.localeCompare(o))}async function hu(e,t,n,o,r,i,s,a){let c=o?.name??n?.name,l=ka(c,e.search.embedding_corpus_max_characters).maxCharacters,d=Jo(e),m=r.map(y=>Sa(y,{providerName:c,maxCharacters:l,fields:d})),f=[],g=null;if(o)try{f=await Gy(o,e,m),g=zt(o.name,fu(e))}catch(y){if(!n)throw new p(`Extension search provider "${o.name}" failed to generate embeddings: ${y instanceof Error?y.message:String(y)}`,u.GENERIC_FAILURE);i.push(`Extension search provider "${o.name}" failed; falling back to built-in provider (${y instanceof Error?y.message:String(y)})`)}if(f.length===0){if(!n)throw new p(`No embedding executor available for reindex mode '${t}'`,u.USAGE);let y=await Aa(n,e,m,{onProgress:k=>{k.phase==="complete"&&(s.batches_completed=k.batch_index),D(a,`embedding_batch_${k.phase} batch=${k.batch_index}/${k.batch_total} size=${k.batch_size} completed_inputs=${k.completed_inputs}/${k.total_inputs}`)}});i.push(...y.warnings),s.batching=y.receipt,f=y.vectors,g=zt(n.name,n.model)}if(D(a,`embedding_complete vectors=${f.length}`),f.length!==r.length)throw new p(`Embedding output size mismatch (expected ${r.length}, received ${f.length})`,u.GENERIC_FAILURE);if(!g)throw new p(`No embedding identity available for reindex mode '${t}'`,u.USAGE);return{vectors:f,embeddingIdentity:g}}async function qy(e,t,n,o,r,i){let s=Object.keys(n);if(t){if(s.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:s.sort((a,c)=>a.localeCompare(c)),settings:o}))}catch(a){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,u.GENERIC_FAILURE)}else s.length>0&&r.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${s.length}`);if(!e)return}e&&await Ca(e,s,{},i)}async function gu(e,t,n,o,r){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:o}))}catch(i){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${i instanceof Error?i.message:String(i)}`,u.GENERIC_FAILURE)}else r.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Ea(e,n)}}function zy(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function Hy(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(o=>({id:o.metadata.id,type:o.metadata.type,status:o.metadata.status,priority:o.metadata.priority,updated_at:o.metadata.updated_at}))}}function By(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Ko(e.settings);if(!t.active&&!e.extensionEmbedding)throw new p(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,u.USAGE);let n=xa(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new p(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,u.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function Wy(e){let t=F(e.settings,T()),n=await Ly(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(o=>({metadata:o.metadata,body:typeof o.body=="string"?o.body:""}))}}async function Vy(e){let t=await Xo(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return _u(e.settings,Ko(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Fn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(Fy))}async function Ky(e){let t=await Xo(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=_u(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),o=new Set(e.metadataDocuments.map(l=>l.metadata.id)),r=Uy(t.entries,o),i=Fn(t.embedding,n);e.forceFullSemantic&&!i&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let s=e.forceFullSemantic||i?e.metadataDocuments:e.metadataDocuments.filter(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),a=new Set(s.map(l=>l.metadata.id)),c=a.size>0?await Ni(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:r,resetRequired:i,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function Jy(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await Ni(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,D(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let o=await hu(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...o,staleDocuments:n,vectorDimension:Yo(o.vectors,"Reindex embeddings")}}async function Yy(e){let t=await hu(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,o=t.embeddingIdentity,r=Yo(n,"Reindex embeddings");if(!(!e.resetRequired&&(Fn(e.ledgerEmbedding,o)||Ta(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:o,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let s=await Jy(e);return n=s.vectors,o=s.embeddingIdentity,r=s.vectorDimension,{vectors:n,embeddingIdentity:o,staleDocuments:s.staleDocuments,vectorDimension:r,resetRequired:!0}}async function Xy(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(D(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new p(`Extension vector adapter "${t}" does not support upserting vectors.`,u.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,D(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof p)throw t;if(!e.activeVectorStore)throw new p(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,u.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),D(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){D(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Ia(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,D(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new p(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,u.USAGE)}function Zy(e,t){return e.map((n,o)=>({id:n.metadata.id,vector:Pi(t[o],`reindex embeddings output at index ${o}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function Qy(e){D(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await Yy({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(D(e.progressEnabled,"vector_reset_start"),await qy(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),D(e.progressEnabled,"vector_reset_complete")):await gu(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=Zy(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await Xy({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Ra(t.embeddingIdentity,t.vectorDimension)}}async function eb(e){let t=await Ky(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(i=>[i.metadata.id,i.metadata.updated_at]));if(D(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return D(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await gu(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let o=await Qy({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let r=new Map(o.staleDocuments.map(i=>[i.metadata.id,i]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(i=>r.get(i.metadata.id)??i),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:o.embeddingMetadata}}async function tb(e){let t=an.join(e.pmRoot,$i),n=an.join(e.pmRoot,Fi),o=Jo(e.settings),r=e.documentsForKeywordArtifacts.map(s=>JSON.stringify(My(s,e.mode,o))).join(`
2286
2286
  `);D(e.progressEnabled,"writing keyword artifacts"),await se(t,`${JSON.stringify(e.manifest,null,2)}
2287
2287
  `),await se(n,`${r}
2288
- `);let i=[];if(e.mode!=="keyword")try{D(e.progressEnabled,"writing vectorization status ledger"),await Ra(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){i.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return i}async function eb(e,t){let n=Fy(e.mode),o=$y(e),r=e.full===!0;D(o,`start mode=${n}`);let i=x(process.cwd(),t.path);await P(i);let s=da(await I(i)).settings,a=null;try{a=await Le(i,ma,s.locks.ttl_seconds,C(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof p&&c.exitCode===u.CONFLICT?new p("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",u.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=Ly(s),l=My(s),d=zy({requestedMode:n,pmRoot:i,settings:s,extensionEmbedding:c,extensionVectorAdapter:l}),m=n;D(o,"loading item corpus");let f=await Hy({pmRoot:i,settings:s}),g=f.warnings,{documentCandidates:y,metadataDocuments:k}=f;D(o,`loaded_items=${k.length}`);let b=S(),v=qy(m,b,k),_=an.join(i,$i),A=an.join(i,Fi),N=m==="keyword"?await Ni(i,y,s.schema,g):k,O=[],B={},$=null,R=Uy(m);if(m==="keyword"&&await By({pmRoot:i,settings:s,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:g}),m!=="keyword"){let ne=await Zy({pmRoot:i,settings:s,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:y,metadataDocuments:k,documentsForKeywordArtifacts:N,forceFullSemantic:r,reindexWarnings:g,semanticWarnings:O,semanticSummary:R,progressEnabled:o});N=ne.documentsForKeywordArtifacts,B=ne.vectorizationLedgerEntries,$=ne.vectorizationEmbeddingMetadata}let ie=await Qy({pmRoot:i,mode:m,manifest:v,documentsForKeywordArtifacts:N,settings:s,vectorizationLedgerEntries:B,vectorizationEmbeddingMetadata:$,progressEnabled:o}),Tt=[...await G({path:_,scope:"project",op:"reindex:manifest"}),...await G({path:A,scope:"project",op:"reindex:embeddings"}),...await Ks({mode:m,total_items:k.length})];return D(o,"done"),{ok:!0,mode:m,total_items:k.length,semantic:R,artifacts:{manifest:$i,embeddings:Fi},warnings:[...g,...O,...ie,...Tt],generated_at:b}}finally{await a?.()}}var cn=Symbol("pm.active-extension-host-context");function Q(e){return{fullChangedFields:!0,options:e}}var w=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[cn]=!0,n}run(t,n={}){return cb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let o=x(this.defaults.cwd??process.cwd(),this.defaults.path),r=async()=>{let c=await nt(o,()=>I(o));return t({pmRoot:o,author:C(this.defaults.author,c.author_default)})};if(this.defaults[cn]===!0){let c=process.cwd(),l=()=>bu(o,Bt({path:o}),void 0,c,r);return n?nt(o,l):l()}let i=Rt()!==void 0;i&&Di(this.defaults.cwd);let s=i?void 0:this.defaults.cwd,a=()=>wu({...this.defaults,cwd:s,path:o},r);return n?nt(o,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-ER3OWOPV.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-ER3OWOPV.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,o)=>this.withItemTransactionContext(async r=>(await import("./item-transaction-ER3OWOPV.js")).abandonItemTransaction({...o,...r,transactionId:n}));return{status:n=>this.withItemTransactionContext(async o=>(await import("./item-transaction-ER3OWOPV.js")).readItemTransaction(o.pmRoot,n),!0),abandon:t,supersede:(n,o,r)=>t(n,{...r,supersededBy:o})}}readItemRevision(t){return this.withItemTransactionContext(async({pmRoot:n})=>(await import("./item-revision-WNUDY5DM.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let o=await import("./item-revision-WNUDY5DM.js"),r="",i=await this.withItemTransactionContext(({pmRoot:a})=>(r=a,o.bindExpectedItemRevisions(t,{pmRoot:a}))),s=this.defaults.noExtensions===!0&&this.defaults[cn]!==!0;return o.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",r,...s?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Od(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return eo(await this.list(Fr(t)),t)}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},o={}){return this.runTyped("graph",{subcommand:t,...n,options:o})}async append(t,n,o={}){return Oc(o,"append"),await this.runTyped("append",{id:t,...Q(st(o,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,o,r,i={}){return this.runTyped("config",{scope:t,configAction:n,...o===void 0?{}:{key:o},...r===void 0?{}:{value:r},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,o={}){return this.runTyped("schema",{name:n,options:{...o,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){let{type:o,...r}=n;return this.runTyped("schema",{name:t,options:{...r,fieldType:o,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,o,r){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-field",to:n,...r?{fieldTypeScope:r}:{}}})}schemaRemapStatus(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,o={},r,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...r===void 0?{}:{stepRef:r},...i===void 0?{}:{reorderTo:i},options:st(o,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,o){return this.plan("update-step",t,o,n)}planCompleteStep(t,n,o={}){return this.plan("complete-step",t,o,n)}planBlockStep(t,n,o){return this.plan("block-step",t,o,n)}planReorderStep(t,n,o,r={}){return this.plan("reorder-step",t,r,n,o)}planRemoveStep(t,n,o={}){return this.plan("remove-step",t,o,n)}planLink(t,n,o){return this.plan("link",t,o,n)}planUnlink(t,n,o){return this.plan("unlink",t,o,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Q(t))}update(t,n={}){return this.runTyped("update",{id:t,...Q(n)})}reopen(t,n,o={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:o})}close(t,n,o={}){return this.runTyped("close",{id:t,reason:n,...Q(o)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Q(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Q(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Q(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Q(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Q(n)})}restore(t,n,o={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...o,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Q(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Q(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Q(n)})}closeTask(t,n,o={}){return this.runTyped("close-task",{id:t,reason:n,...Q(o)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function eR(e={},t={}){return new w(t).context(e)}function tR(e={},t={}){return new w(t).list(e)}function nR(e={},t={}){return new w(t).listAllComplete(e)}function oR(e,t={},n={}){return new w(n).search(e,t)}function rR(e,t={},n={}){return new w(n).get(e,t)}function iR(e={},t={}){return new w(t).next(e)}function sR(e={},t={}){return new w(t).aggregate(e)}function aR(e={},t={}){return new w(t).stats(e)}function cR(e={},t={}){return new w(t).duplicates(e)}function lR(e,t={},n={}){return new w(n).comments(e,t)}function dR(e,t={},n={}){return new w(n).notes(e,t)}function mR(e,t={},n={}){return new w(n).learnings(e,t)}function pR(e,t={},n={}){return new w(n).files(e,t)}function uR(e,t={},n={}){return new w(n).filesDiscover(e,t)}function fR(e,t={}){return new w(t).filesLookup(e)}function _R(e,t={},n={}){return new w(n).docs(e,t)}function hR(e,t={},n={}){return new w(n).deps(e,t)}function gR(e,t={},n={},o={}){return new w(o).graph(e,t,n)}function yR(e,t,n={},o={}){return new w(o).append(e,t,n)}function bR(e,t={},n={}){return new w(n).init(e,t)}function wR(e,t,n,o,r={},i={}){return new w(i).config(e,t,n,o,r)}function vR(e,t={},n={}){return new w(n).schema(e,t)}function kR(e={}){return new w(e).schemaList()}function SR(e,t={}){return new w(t).schemaShow(e)}function AR(e,t={},n={}){return new w(n).schemaAddType(e,t)}function xR(e,t={},n={}){return new w(n).schemaRemoveType(e,t)}function IR(e,t={},n={}){return new w(n).schemaAddStatus(e,t)}function ER(e,t={},n={}){return new w(n).schemaRemoveStatus(e,t)}function CR(e,t={},n={}){return new w(n).schemaAddField(e,t)}function RR(e,t={},n={}){return new w(n).schemaRemoveField(e,t)}function TR(e={}){return new w(e).schemaListFields()}function OR(e,t={}){return new w(t).schemaShowField(e)}function $R(e,t={},n={}){return new w(n).schemaApplyPreset(e,t)}function FR(e={},t={}){return new w(t).schemaInferTypes(e)}function PR(e,t,n,o={}){return new w(o).schemaRenameType(e,t,n)}function NR(e,t,n,o,r={}){return new w(r).schemaRenameField(e,t,n,o)}function LR(e,t,n,o={}){return new w(o).schemaRemapStatus(e,t,n)}function MR(e,t={}){return new w(t).schemaShowStatus(e)}function DR(e,t={},n={}){return new w(n).profile(e,t)}function jR(e={}){return new w(e).profileList()}function GR(e,t={}){return new w(t).profileShow(e)}function UR(e,t={},n={}){return new w(n).profileApply(e,t)}function qR(e,t={}){return new w(t).profileLint(e)}function zR(e={},t={}){return new w(t).validate(e)}function HR(e={},t={}){return new w(t).health(e)}function BR(e={},t={}){return new w(t).gc(e)}function WR(e,t,n={}){return new w(n).historyRedact(e,t)}function VR(e,t={},n={}){return new w(n).historyRepair(e,t)}function KR(e={},t={}){return new w(t).historyRepairAll(e)}function JR(e,t={},n={}){return new w(n).historyCompact(e,t)}function YR(e,t={}){return new w(t).historyCompactBulk(e)}function XR(e={},t={}){return new w(t).create(e)}function ZR(e,t={},n={}){return new w(n).update(e,t)}function QR(e,t,n={},o={}){return new w(o).reopen(e,t,n)}function eT(e,t,n={},o={}){return new w(o).close(e,t,n)}function tT(e,t={},n={}){return new w(n).claim(e,t)}function nT(e={},t={}){return new w(t).claimNext(e)}function oT(e,t={},n={}){return new w(n).release(e,t)}function rT(e,t={},n={}){return new w(n).copy(e,t)}function iT(e,t={},n={}){return new w(n).delete(e,t)}function sT(e,t,n={},o={}){return new w(o).restore(e,t,n)}function aT(e,t={},n={}){return new w(n).focus(e,t)}function cT(e,t={},n={}){return new w(n).startTask(e,t)}function lT(e,t={},n={}){return new w(n).pauseTask(e,t)}function dT(e,t,n={},o={}){return new w(o).closeTask(e,t,n)}function mT(e,t={},n={}){return new w(n).extension(e,t)}function pT(e={},t={}){return new w(t).extensionList(e)}function uT(e,t={},n={}){return new w(n).extensionActivate(e,t)}function fT(e,t={},n={}){return new w(n).extensionDeactivate(e,t)}function _T(e,t={},n={}){return new w(n).package(e,t)}function hT(e={},t={}){return new w(t).packageList(e)}function gT(e,t={},n={}){return new w(n).packageInstall(e,t)}function yT(e,t={},n={}){return new w(n).packageUninstall(e,t)}function bT(e={},t={}){return new w(t).packageDoctor(e)}function wT(e,t={},n={}){return new w(n).packageManage(e,t)}function vT(e,t={},n={}){return new w(n).packageDescribe(e,t)}function kT(e={},t={}){return new w(t).packageReload(e)}function ST(e={},t={}){return new w(t).packageCatalog(e)}function AT(e,t={},n={}){return new w(n).packageActivate(e,t)}function xT(e,t={},n={}){return new w(n).packageDeactivate(e,t)}function IT(e,t={},n={}){return new w(n).upgrade(e,t)}async function ET(e,t={}){let n=typeof e=="string"?{...t,pmRoot:e}:e??t,o={json:!0,quiet:n.quiet??!0,noExtensions:n.noExtensions??!1,noPager:!0,profile:n.profile??!1,path:n.pmRoot};return Gn(n,o)}var gu=Bs(),ko=new tb;function ln(e){try{return nb(e)}catch{return Mi.resolve(e)}}function Rt(){let e=ko.getStore();for(;e!==void 0&&!e.live;)e=e.parent;return e}async function Ct(e,t,n,o=!0){let r={root:ln(e),active:t,live:!0,parent:Rt(),ready:o};try{return await ko.run(r,n)}finally{r.live=!1}}function Di(e){if(e===void 0||ln(e)===ln(process.cwd()))return;let t="Omit cwd inside an open extension scope and address the tracker with path, or make the call outside the scope.";throw new p(`A nested SDK call cannot change the working directory to "${e}" while its caller's extension scope is open. ${t}`,u.USAGE,{code:"invalid_argument_value",reason:"nested_cwd_unavailable",changed:!1,field:"cwd",required:t,nextSteps:[t]})}function ji(e,t,n,o){let r=Rt();if(r===void 0)return;let i=r===ko.getStore(),s=r.root===ln(e);if(s&&!r.ready){let a="Do the work from a command or hook handler, after the tracker's extensions have activated.";throw new p(`An extension lifecycle callback cannot run SDK work for tracker ${r.root} while its extensions activate or deactivate. ${a}`,u.USAGE,{code:"invalid_argument_value",reason:"extension_scope_not_ready",changed:!1,required:a,nextSteps:[a]})}return i&&s&&t.noExtensions!==!0?o(r.active):No(()=>Ct(e,null,()=>Li(t,n,a=>Ct(e,a,()=>o(a))),!1))}function bu(e,t,n,o,r){let i=ko.getStore();if(i===void 0)return r(null);let s=Rt(),a={...t,noExtensions:!1};return s===void 0?Ct(e,null,()=>Gi(a,n===void 0?void 0:o,o,c=>Ct(e,c,()=>r(c))),!1):s===i&&s.ready&&s.root===ln(e)?r(null):ji(e,a,o,r)}function vo(){Lo(Ds()),Mo(js()),Do(Gs()),jo(Us()),Go(qs()),Uo(zs()),qo(Hs())}async function Gi(e,t,n,o){return No(()=>t===void 0?gu.read(()=>Li(e,n,o)):gu.write(()=>ib(t,()=>Li(e,n,o))))}async function wu(e,t){let n=e.cwd,o=n===void 0?process.cwd():Mi.resolve(n),r=x(o,e.path),i=Bt({path:r,noExtensions:e.noExtensions});Rt()!==void 0&&Di(n);let s=ji(r,i,o,()=>t());return s!==void 0?s:Gi(i,n===void 0?void 0:o,o,a=>Ct(r,a,t))}function CT(e,t){return wu({path:e},t)}function ob(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:Oa(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function Li(e,t,n){let o=x(t,e.path);if(e.noExtensions)return vo(),Er({pmRoot:o},()=>n(null));if(!await ke(Se(o)))return vo(),n(null);let r=null,i;try{let s=await I(o),a=await vn({pmRoot:o,settings:s,cwd:t,noExtensions:!1}),c=await Sn({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},Lo(c.hooks),Mo(c.commands),Do(c.parsers),jo(c.preflight),Go(c.services),Uo(c.renderers),qo(c.registrations),r={registrations:c.registrations,commands:c.commands,pmRoot:o,packages:a.loaded}}catch(s){vo(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",ob(s))}try{return await Er({pmRoot:o,packages:r?.packages},()=>n(r))}finally{vo(),i&&await kn(i.loadResult,i.activationResult).catch(()=>{})}}function vu(e,t){let n=De(e);return t?.registrations.commands.find(o=>De(o.action)===n)?.command??t?.commands.handlers.find(o=>De(o.command)===n)?.command}async function rb(e,t,n,o,r){if(!r)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let i=vu(e,r);if(!i)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let s=typeof n.author=="string"?n.author:o.author,a=sr(i),c=Bc(ar(t,n),Hc(r.registrations,a),a,Rd(a)),l=await Js({command:a,args:U(n.args??t.args),options:c,global:{...o,author:s},pm_root:r.pmRoot,sdk:Cd(r.pmRoot,w.forActiveExtensionHost({pmRoot:r.pmRoot,author:s}),s,a)});if(!l.handled){if(Object.hasOwn(l,"cause"))throw Ta(i,l);let d=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new p(`Unsupported native pm action: ${e}${d}`,u.USAGE)}return l.result}async function ib(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function sb(e){let t=K(e,"action"),n=De(t),o=be(Pr,n),r=o?.action??n,i={...e,action:r};return o?.options!==void 0&&(i.options={...o.options,...Nt(e.options)}),r==="package"&&(i.options={...Nt(i.options),vocabulary:"package"}),{action:r,args:i}}function ab(e,t,n,o){let r=e[cn]===!0,i=t.noExtensions===!0&&!r?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",x(o,t.path),...i];let s=ds(t,o);return[...t.noExtensions===!0?s.slice(0,-1):s,...i]}async function cb(e){let t=sb(e),n=Bt(t.args);ls(n);let o=jc(t.action),r=h(t.args,"cwd"),i=r===void 0?process.cwd():Mi.resolve(r);t.action==="init"&&(n[gl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=x(i,n.path));let{expectHash:s,dispatchArgs:a}=zc(t.args),c=async l=>{if(s===void 0)return yu(t.action,a,n,l);let{dispatchWithExpectedItemRevisions:d}=await import("./item-revision-WNUDY5DM.js");return d({action:t.action,expectHash:s,defaultId:h(a,"id")??h(Nt(a.options),"id"),options:Nt(a.options),background:a.background,pmRoot:x(i,n.path),invocation:{scopeArgs:ab(e,n,r,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>yu(t.action,a,n,l)})};try{if(t.action==="history-attest")return await c(null);let l=x(i,n.path);if(Rt()!==void 0&&Di(r),e[cn]===!0)return await bu(l,n,r,i,c);let d=ji(l,n,i,c);return d!==void 0?await d:await Gi(n,r===void 0?void 0:i,i,m=>Ct(l,m,()=>c(m)))}finally{o&&yi()}}function RT(e=Yi){return e.map(t=>{let n=De(t),o=be(Pr,n),r=o?.action??n,i=be(gi,r)!==void 0;return{action:t,resolved_action:r,covered:i,route:i?o?"alias":"native":"missing"}})}async function yu(e,t,n,o){let r=be(gi,e),i=ir(t,e,{nativeAction:r!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:d}=await import("./mutation-admission-AVOOT3KH.js");await d(e,t,i,n.path,Mc[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:d}=await import("./mutation-admission-AVOOT3KH.js");await d(t,i,n.path)}let s=r?void 0:vu(e,o),a=s===void 0?e:`extension:${s}`;Rs(a,i),Ts(a,i);let c={action:e,args:t,options:i,id:h(t,"id"),force:t.force===!0||i.force===!0,global:n,activeExtensions:o},l=r?await r(c):await rb(e,t,i,n,o);if(e==="history-attest")return l;{let d=Ls(a,i,l);return await kd(x(process.cwd(),n.path),d),d}}var lb={closeManyOptionsFromFlat:Dn,extensionOptionsFromArgs:ar,globalOptions:Bt,mutationListOptions:Gc,normalizeActionName:De,normalizeCommandPath:sr,normalizeMcpUpdateOptions:qc,normalizeMcpOptionsArrays:Dc,optionsWithAuthor:ir,readRequiredString:K,readScalarString:Pc,readScalarStringAllowBlank:Nc,readStringArray:U,updateManyOptionsFromFlat:jn,withAddNoteOption:Wt,withFilesDiscoveryOptions:Mn,withMutationCompaction:j};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=lb);export{Ir as a,vd as b,Iu as c,Cu as d,Ru as e,Er as f,Yt as g,Ad as h,Zt as i,Zn as j,Cd as k,Rd as l,Uu as m,Qn as n,Fr as o,Td as p,eo as q,Ju as r,Pd as s,Md as t,jd as u,zd as v,Dr as w,jr as x,Gr as y,Ur as z,Cf as A,Vr as B,sm as C,mm as D,um as E,pt as F,ii as G,oh as H,sk as I,ak as J,ci as K,_m as L,Ak as M,xk as N,gm as O,wm as P,Bk as Q,wh as R,_i as S,kh as T,Sh as U,Fm as V,Pm as W,Nm as X,Lm as Y,Mm as Z,gS as _,yS as $,bS as aa,wS as ba,Dm as ca,Um as da,lo as ea,Wm as fa,Vm as ga,Km as ha,K as ia,yi as ja,Jx as ka,Yx as la,Xx as ma,Zx as na,Qx as oa,ip as pa,eI as qa,Ig as ra,Rg as sa,Fg as ta,Pg as ua,Ng as va,z as wa,Lg as xa,Mg as ya,Dg as za,jg as Aa,wi as Ba,lp as Ca,_t as Da,bi as Ea,dp as Fa,Gg as Ga,mp as Ha,Ug as Ia,qg as Ja,zg as Ka,Hg as La,Bg as Ma,Wg as Na,Qg as Oa,_p as Pa,ty as Qa,cy as Ra,_y as Sa,gy as Ta,Ry as Ua,eb as Va,w as Wa,eR as Xa,tR as Ya,nR as Za,oR as _a,rR as $a,iR as ab,sR as bb,aR as cb,cR as db,lR as eb,dR as fb,mR as gb,pR as hb,uR as ib,fR as jb,_R as kb,hR as lb,gR as mb,yR as nb,bR as ob,wR as pb,vR as qb,kR as rb,SR as sb,AR as tb,xR as ub,IR as vb,ER as wb,CR as xb,RR as yb,TR as zb,OR as Ab,$R as Bb,FR as Cb,PR as Db,NR as Eb,LR as Fb,MR as Gb,DR as Hb,jR as Ib,GR as Jb,UR as Kb,qR as Lb,zR as Mb,HR as Nb,BR as Ob,WR as Pb,VR as Qb,KR as Rb,JR as Sb,YR as Tb,XR as Ub,ZR as Vb,QR as Wb,eT as Xb,tT as Yb,nT as Zb,oT as _b,rT as $b,iT as ac,sT as bc,aT as cc,cT as dc,lT as ec,dT as fc,mT as gc,pT as hc,uT as ic,fT as jc,_T as kc,hT as lc,gT as mc,yT as nc,bT as oc,wT as pc,vT as qc,kT as rc,ST as sc,AT as tc,xT as uc,IT as vc,ET as wc,wu as xc,CT as yc,cb as zc,RT as Ac};
2289
- //# sourceMappingURL=chunk-O23KTJL6.js.map
2288
+ `);let i=[];if(e.mode!=="keyword")try{D(e.progressEnabled,"writing vectorization status ledger"),await Oa(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){i.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return i}async function nb(e,t){let n=Ny(e.mode),o=Py(e),r=e.full===!0;D(o,`start mode=${n}`);let i=x(process.cwd(),t.path);await P(i);let s=pa(await I(i)).settings,a=null;try{a=await Le(i,ua,s.locks.ttl_seconds,C(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof p&&c.exitCode===u.CONFLICT?new p("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",u.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=Dy(s),l=jy(s),d=By({requestedMode:n,pmRoot:i,settings:s,extensionEmbedding:c,extensionVectorAdapter:l}),m=n;D(o,"loading item corpus");let f=await Wy({pmRoot:i,settings:s}),g=f.warnings,{documentCandidates:y,metadataDocuments:k}=f;D(o,`loaded_items=${k.length}`);let b=S(),v=Hy(m,b,k),_=an.join(i,$i),A=an.join(i,Fi),N=m==="keyword"?await Ni(i,y,s.schema,g):k,O=[],B={},$=null,R=zy(m);if(m==="keyword"&&await Vy({pmRoot:i,settings:s,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:g}),m!=="keyword"){let ne=await eb({pmRoot:i,settings:s,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:y,metadataDocuments:k,documentsForKeywordArtifacts:N,forceFullSemantic:r,reindexWarnings:g,semanticWarnings:O,semanticSummary:R,progressEnabled:o});N=ne.documentsForKeywordArtifacts,B=ne.vectorizationLedgerEntries,$=ne.vectorizationEmbeddingMetadata}let ie=await tb({pmRoot:i,mode:m,manifest:v,documentsForKeywordArtifacts:N,settings:s,vectorizationLedgerEntries:B,vectorizationEmbeddingMetadata:$,progressEnabled:o}),Tt=[...await G({path:_,scope:"project",op:"reindex:manifest"}),...await G({path:A,scope:"project",op:"reindex:embeddings"}),...await Ys({mode:m,total_items:k.length})];return D(o,"done"),{ok:!0,mode:m,total_items:k.length,semantic:R,artifacts:{manifest:$i,embeddings:Fi},warnings:[...g,...O,...ie,...Tt],generated_at:b}}finally{await a?.()}}var cn=Symbol("pm.active-extension-host-context");function ee(e){return{fullChangedFields:!0,options:e}}var w=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[cn]=!0,n}run(t,n={}){return db({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let o=x(this.defaults.cwd??process.cwd(),this.defaults.path),r=async()=>{let c=await nt(o,()=>I(o));return t({pmRoot:o,author:C(this.defaults.author,c.author_default)})};if(this.defaults[cn]===!0){let c=process.cwd(),l=()=>wu(o,Bt({path:o}),void 0,c,r);return n?nt(o,l):l()}let i=Rt()!==void 0;i&&Di(this.defaults.cwd);let s=i?void 0:this.defaults.cwd,a=()=>vu({...this.defaults,cwd:s,path:o},r);return n?nt(o,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-4XC74ULD.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-4XC74ULD.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,o)=>this.withItemTransactionContext(async r=>(await import("./item-transaction-4XC74ULD.js")).abandonItemTransaction({...o,...r,transactionId:n}));return{status:n=>this.withItemTransactionContext(async o=>(await import("./item-transaction-4XC74ULD.js")).readItemTransaction(o.pmRoot,n),!0),abandon:t,supersede:(n,o,r)=>t(n,{...r,supersededBy:o})}}readItemRevision(t){return this.withItemTransactionContext(async({pmRoot:n})=>(await import("./item-revision-O7L3AA2W.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let o=await import("./item-revision-O7L3AA2W.js"),r="",i=await this.withItemTransactionContext(({pmRoot:a})=>(r=a,o.bindExpectedItemRevisions(t,{pmRoot:a}))),s=this.defaults.noExtensions===!0&&this.defaults[cn]!==!0;return o.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",r,...s?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return $d(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return eo(await this.list(Fr(t)),t)}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},o={}){return this.runTyped("graph",{subcommand:t,...n,options:o})}async append(t,n,o={}){return Oc(o,"append"),await this.runTyped("append",{id:t,...ee(st(o,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,o,r,i={}){return this.runTyped("config",{scope:t,configAction:n,...o===void 0?{}:{key:o},...r===void 0?{}:{value:r},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,o={}){return this.runTyped("schema",{name:n,options:{...o,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){let{type:o,...r}=n;return this.runTyped("schema",{name:t,options:{...r,fieldType:o,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,o,r){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-field",to:n,...r?{fieldTypeScope:r}:{}}})}schemaRemapStatus(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,o={},r,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...r===void 0?{}:{stepRef:r},...i===void 0?{}:{reorderTo:i},options:st(o,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,o){return this.plan("update-step",t,o,n)}planCompleteStep(t,n,o={}){return this.plan("complete-step",t,o,n)}planBlockStep(t,n,o){return this.plan("block-step",t,o,n)}planReorderStep(t,n,o,r={}){return this.plan("reorder-step",t,r,n,o)}planRemoveStep(t,n,o={}){return this.plan("remove-step",t,o,n)}planLink(t,n,o){return this.plan("link",t,o,n)}planUnlink(t,n,o){return this.plan("unlink",t,o,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",ee(t))}update(t,n={}){return this.runTyped("update",{id:t,...ee(n)})}reopen(t,n,o={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:o})}close(t,n,o={}){return this.runTyped("close",{id:t,reason:n,...ee(o)})}claim(t,n={}){return this.runTyped("claim",{id:t,...ee(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...ee(t)})}release(t,n={}){return this.runTyped("release",{id:t,...ee(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...ee(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...ee(n)})}restore(t,n,o={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...o,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...ee(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...ee(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...ee(n)})}closeTask(t,n,o={}){return this.runTyped("close-task",{id:t,reason:n,...ee(o)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function nR(e={},t={}){return new w(t).context(e)}function oR(e={},t={}){return new w(t).list(e)}function rR(e={},t={}){return new w(t).listAllComplete(e)}function iR(e,t={},n={}){return new w(n).search(e,t)}function sR(e,t={},n={}){return new w(n).get(e,t)}function aR(e={},t={}){return new w(t).next(e)}function cR(e={},t={}){return new w(t).aggregate(e)}function lR(e={},t={}){return new w(t).stats(e)}function dR(e={},t={}){return new w(t).duplicates(e)}function mR(e,t={},n={}){return new w(n).comments(e,t)}function pR(e,t={},n={}){return new w(n).notes(e,t)}function uR(e,t={},n={}){return new w(n).learnings(e,t)}function fR(e,t={},n={}){return new w(n).files(e,t)}function _R(e,t={},n={}){return new w(n).filesDiscover(e,t)}function hR(e,t={}){return new w(t).filesLookup(e)}function gR(e,t={},n={}){return new w(n).docs(e,t)}function yR(e,t={},n={}){return new w(n).deps(e,t)}function bR(e,t={},n={},o={}){return new w(o).graph(e,t,n)}function wR(e,t,n={},o={}){return new w(o).append(e,t,n)}function vR(e,t={},n={}){return new w(n).init(e,t)}function kR(e,t,n,o,r={},i={}){return new w(i).config(e,t,n,o,r)}function SR(e,t={},n={}){return new w(n).schema(e,t)}function AR(e={}){return new w(e).schemaList()}function xR(e,t={}){return new w(t).schemaShow(e)}function IR(e,t={},n={}){return new w(n).schemaAddType(e,t)}function ER(e,t={},n={}){return new w(n).schemaRemoveType(e,t)}function CR(e,t={},n={}){return new w(n).schemaAddStatus(e,t)}function RR(e,t={},n={}){return new w(n).schemaRemoveStatus(e,t)}function TR(e,t={},n={}){return new w(n).schemaAddField(e,t)}function OR(e,t={},n={}){return new w(n).schemaRemoveField(e,t)}function $R(e={}){return new w(e).schemaListFields()}function FR(e,t={}){return new w(t).schemaShowField(e)}function PR(e,t={},n={}){return new w(n).schemaApplyPreset(e,t)}function NR(e={},t={}){return new w(t).schemaInferTypes(e)}function LR(e,t,n,o={}){return new w(o).schemaRenameType(e,t,n)}function MR(e,t,n,o,r={}){return new w(r).schemaRenameField(e,t,n,o)}function DR(e,t,n,o={}){return new w(o).schemaRemapStatus(e,t,n)}function jR(e,t={}){return new w(t).schemaShowStatus(e)}function GR(e,t={},n={}){return new w(n).profile(e,t)}function UR(e={}){return new w(e).profileList()}function qR(e,t={}){return new w(t).profileShow(e)}function zR(e,t={},n={}){return new w(n).profileApply(e,t)}function HR(e,t={}){return new w(t).profileLint(e)}function BR(e={},t={}){return new w(t).validate(e)}function WR(e={},t={}){return new w(t).health(e)}function VR(e={},t={}){return new w(t).gc(e)}function KR(e,t,n={}){return new w(n).historyRedact(e,t)}function JR(e,t={},n={}){return new w(n).historyRepair(e,t)}function YR(e={},t={}){return new w(t).historyRepairAll(e)}function XR(e,t={},n={}){return new w(n).historyCompact(e,t)}function ZR(e,t={}){return new w(t).historyCompactBulk(e)}function QR(e={},t={}){return new w(t).create(e)}function eT(e,t={},n={}){return new w(n).update(e,t)}function tT(e,t,n={},o={}){return new w(o).reopen(e,t,n)}function nT(e,t,n={},o={}){return new w(o).close(e,t,n)}function oT(e,t={},n={}){return new w(n).claim(e,t)}function rT(e={},t={}){return new w(t).claimNext(e)}function iT(e,t={},n={}){return new w(n).release(e,t)}function sT(e,t={},n={}){return new w(n).copy(e,t)}function aT(e,t={},n={}){return new w(n).delete(e,t)}function cT(e,t,n={},o={}){return new w(o).restore(e,t,n)}function lT(e,t={},n={}){return new w(n).focus(e,t)}function dT(e,t={},n={}){return new w(n).startTask(e,t)}function mT(e,t={},n={}){return new w(n).pauseTask(e,t)}function pT(e,t,n={},o={}){return new w(o).closeTask(e,t,n)}function uT(e,t={},n={}){return new w(n).extension(e,t)}function fT(e={},t={}){return new w(t).extensionList(e)}function _T(e,t={},n={}){return new w(n).extensionActivate(e,t)}function hT(e,t={},n={}){return new w(n).extensionDeactivate(e,t)}function gT(e,t={},n={}){return new w(n).package(e,t)}function yT(e={},t={}){return new w(t).packageList(e)}function bT(e,t={},n={}){return new w(n).packageInstall(e,t)}function wT(e,t={},n={}){return new w(n).packageUninstall(e,t)}function vT(e={},t={}){return new w(t).packageDoctor(e)}function kT(e,t={},n={}){return new w(n).packageManage(e,t)}function ST(e,t={},n={}){return new w(n).packageDescribe(e,t)}function AT(e={},t={}){return new w(t).packageReload(e)}function xT(e={},t={}){return new w(t).packageCatalog(e)}function IT(e,t={},n={}){return new w(n).packageActivate(e,t)}function ET(e,t={},n={}){return new w(n).packageDeactivate(e,t)}function CT(e,t={},n={}){return new w(n).upgrade(e,t)}async function RT(e,t={}){let n=typeof e=="string"?{...t,pmRoot:e}:e??t,o={json:!0,quiet:n.quiet??!0,noExtensions:n.noExtensions??!1,noPager:!0,profile:n.profile??!1,path:n.pmRoot};return Gn(n,o)}var yu=Vs(),ko=new ob;function ln(e){try{return rb(e)}catch{return Mi.resolve(e)}}function Rt(){let e=ko.getStore();for(;e!==void 0&&!e.live;)e=e.parent;return e}async function Ct(e,t,n,o=!0){let r={root:ln(e),active:t,live:!0,parent:Rt(),ready:o};try{return await ko.run(r,n)}finally{r.live=!1}}function Di(e){if(e===void 0||ln(e)===ln(process.cwd()))return;let t="Omit cwd inside an open extension scope and address the tracker with path, or make the call outside the scope.";throw new p(`A nested SDK call cannot change the working directory to "${e}" while its caller's extension scope is open. ${t}`,u.USAGE,{code:"invalid_argument_value",reason:"nested_cwd_unavailable",changed:!1,field:"cwd",required:t,nextSteps:[t]})}function ji(e,t,n,o){let r=Rt();if(r===void 0)return;let i=r===ko.getStore(),s=r.root===ln(e);if(s&&!r.ready){let a="Do the work from a command or hook handler, after the tracker's extensions have activated.";throw new p(`An extension lifecycle callback cannot run SDK work for tracker ${r.root} while its extensions activate or deactivate. ${a}`,u.USAGE,{code:"invalid_argument_value",reason:"extension_scope_not_ready",changed:!1,required:a,nextSteps:[a]})}return i&&s&&t.noExtensions!==!0?o(r.active):No(()=>Ct(e,null,()=>Li(t,n,a=>Ct(e,a,()=>o(a))),!1))}function wu(e,t,n,o,r){let i=ko.getStore();if(i===void 0)return r(null);let s=Rt(),a={...t,noExtensions:!1};return s===void 0?Ct(e,null,()=>Gi(a,n===void 0?void 0:o,o,c=>Ct(e,c,()=>r(c))),!1):s===i&&s.ready&&s.root===ln(e)?r(null):ji(e,a,o,r)}function vo(){Lo(Gs()),Mo(Us()),Do(qs()),jo(zs()),Go(Hs()),Uo(Bs()),qo(Ws())}async function Gi(e,t,n,o){return No(()=>t===void 0?yu.read(()=>Li(e,n,o)):yu.write(()=>ab(t,()=>Li(e,n,o))))}async function vu(e,t){let n=e.cwd,o=n===void 0?process.cwd():Mi.resolve(n),r=x(o,e.path),i=Bt({path:r,noExtensions:e.noExtensions});Rt()!==void 0&&Di(n);let s=ji(r,i,o,()=>t());return s!==void 0?s:Gi(i,n===void 0?void 0:o,o,a=>Ct(r,a,t))}function TT(e,t){return vu({path:e},t)}function ib(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:Fa(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function Li(e,t,n){let o=x(t,e.path);if(e.noExtensions)return vo(),Er({pmRoot:o},()=>n(null));if(!await ke(Se(o)))return vo(),n(null);let r=null,i;try{let s=await I(o),a=await kn({pmRoot:o,settings:s,cwd:t,noExtensions:!1}),c=await An({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},Lo(c.hooks),Mo(c.commands),Do(c.parsers),jo(c.preflight),Go(c.services),Uo(c.renderers),qo(c.registrations),r={registrations:c.registrations,commands:c.commands,pmRoot:o,packages:a.loaded}}catch(s){vo(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",ib(s))}try{return await Er({pmRoot:o,packages:r?.packages},()=>n(r))}finally{vo(),i&&await Sn(i.loadResult,i.activationResult).catch(()=>{})}}function ku(e,t){let n=De(e);return t?.registrations.commands.find(o=>De(o.action)===n)?.command??t?.commands.handlers.find(o=>De(o.command)===n)?.command}async function sb(e,t,n,o,r){if(!r)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let i=ku(e,r);if(!i)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let s=typeof n.author=="string"?n.author:o.author,a=sr(i),c=Bc(ar(t,n),Hc(r.registrations,a),a,Td(a)),l=await Xs({command:a,args:U(n.args??t.args),options:c,global:{...o,author:s},pm_root:r.pmRoot,sdk:Rd(r.pmRoot,w.forActiveExtensionHost({pmRoot:r.pmRoot,author:s}),s,a)});if(!l.handled){if(Object.hasOwn(l,"cause"))throw $a(i,l);let d=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new p(`Unsupported native pm action: ${e}${d}`,u.USAGE)}return l.result}async function ab(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function cb(e){let t=K(e,"action"),n=De(t),o=be(Pr,n),r=o?.action??n,i={...e,action:r};return o?.options!==void 0&&(i.options={...o.options,...Nt(e.options)}),r==="package"&&(i.options={...Nt(i.options),vocabulary:"package"}),{action:r,args:i}}function lb(e,t,n,o){let r=e[cn]===!0,i=t.noExtensions===!0&&!r?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",x(o,t.path),...i];let s=ds(t,o);return[...t.noExtensions===!0?s.slice(0,-1):s,...i]}async function db(e){let t=cb(e),n=Bt(t.args);ls(n);let o=jc(t.action),r=h(t.args,"cwd"),i=r===void 0?process.cwd():Mi.resolve(r);t.action==="init"&&(n[gl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=x(i,n.path));let{expectHash:s,dispatchArgs:a}=zc(t.args),c=async l=>{if(s===void 0)return bu(t.action,a,n,l);let{dispatchWithExpectedItemRevisions:d}=await import("./item-revision-O7L3AA2W.js");return d({action:t.action,expectHash:s,defaultId:h(a,"id")??h(Nt(a.options),"id"),options:Nt(a.options),background:a.background,pmRoot:x(i,n.path),invocation:{scopeArgs:lb(e,n,r,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>bu(t.action,a,n,l)})};try{if(t.action==="history-attest")return await c(null);let l=x(i,n.path);if(Rt()!==void 0&&Di(r),e[cn]===!0)return await wu(l,n,r,i,c);let d=ji(l,n,i,c);return d!==void 0?await d:await Gi(n,r===void 0?void 0:i,i,m=>Ct(l,m,()=>c(m)))}finally{o&&yi()}}function OT(e=Yi){return e.map(t=>{let n=De(t),o=be(Pr,n),r=o?.action??n,i=be(gi,r)!==void 0;return{action:t,resolved_action:r,covered:i,route:i?o?"alias":"native":"missing"}})}async function bu(e,t,n,o){let r=be(gi,e),i=ir(t,e,{nativeAction:r!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:d}=await import("./mutation-admission-SIUIMAEO.js");await d(e,t,i,n.path,Mc[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:d}=await import("./mutation-admission-SIUIMAEO.js");await d(t,i,n.path)}let s=r?void 0:ku(e,o),a=s===void 0?e:`extension:${s}`;Os(a,i),$s(a,i);let c={action:e,args:t,options:i,id:h(t,"id"),force:t.force===!0||i.force===!0,global:n,activeExtensions:o},l=r?await r(c):await sb(e,t,i,n,o);if(e==="history-attest")return l;{let d=Ds(a,i,l);return await kd(x(process.cwd(),n.path),d),d}}var mb={closeManyOptionsFromFlat:Dn,extensionOptionsFromArgs:ar,globalOptions:Bt,mutationListOptions:Gc,normalizeActionName:De,normalizeCommandPath:sr,normalizeMcpUpdateOptions:qc,normalizeMcpOptionsArrays:Dc,optionsWithAuthor:ir,readRequiredString:K,readScalarString:Pc,readScalarStringAllowBlank:Nc,readStringArray:U,updateManyOptionsFromFlat:jn,withAddNoteOption:Wt,withFilesDiscoveryOptions:Mn,withMutationCompaction:j};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=mb);export{Ir as a,vd as b,Eu as c,Ru as d,Tu as e,Er as f,Yt as g,Ad as h,Zt as i,Zn as j,Rd as k,Td as l,zu as m,Qn as n,Fr as o,Od as p,eo as q,Xu as r,Nd as s,Dd as t,Gd as u,Hd as v,Dr as w,jr as x,Gr as y,Ur as z,Tf as A,Vr as B,am as C,pm as D,fm as E,pt as F,ii as G,ih as H,ck as I,lk as J,ci as K,hm as L,Ik as M,Ek as N,ym as O,vm as P,Vk as Q,kh as R,_i as S,Ah as T,xh as U,Pm as V,Nm as W,Lm as X,Mm as Y,Dm as Z,bS as _,wS as $,vS as aa,kS as ba,jm as ca,qm as da,lo as ea,Vm as fa,Km as ga,Jm as ha,K as ia,yi as ja,Xx as ka,Zx as la,Qx as ma,eI as na,tI as oa,sp as pa,nI as qa,Cg as ra,Og as sa,Ng as ta,Lg as ua,Mg as va,z as wa,Dg as xa,jg as ya,Gg as za,Ug as Aa,wi as Ba,dp as Ca,_t as Da,bi as Ea,mp as Fa,qg as Ga,pp as Ha,zg as Ia,Hg as Ja,Bg as Ka,Wg as La,Vg as Ma,Kg as Na,ty as Oa,hp as Pa,oy as Qa,dy as Ra,gy as Sa,by as Ta,Oy as Ua,nb as Va,w as Wa,nR as Xa,oR as Ya,rR as Za,iR as _a,sR as $a,aR as ab,cR as bb,lR as cb,dR as db,mR as eb,pR as fb,uR as gb,fR as hb,_R as ib,hR as jb,gR as kb,yR as lb,bR as mb,wR as nb,vR as ob,kR as pb,SR as qb,AR as rb,xR as sb,IR as tb,ER as ub,CR as vb,RR as wb,TR as xb,OR as yb,$R as zb,FR as Ab,PR as Bb,NR as Cb,LR as Db,MR as Eb,DR as Fb,jR as Gb,GR as Hb,UR as Ib,qR as Jb,zR as Kb,HR as Lb,BR as Mb,WR as Nb,VR as Ob,KR as Pb,JR as Qb,YR as Rb,XR as Sb,ZR as Tb,QR as Ub,eT as Vb,tT as Wb,nT as Xb,oT as Yb,rT as Zb,iT as _b,sT as $b,aT as ac,cT as bc,lT as cc,dT as dc,mT as ec,pT as fc,uT as gc,fT as hc,_T as ic,hT as jc,gT as kc,yT as lc,bT as mc,wT as nc,vT as oc,kT as pc,ST as qc,AT as rc,xT as sc,IT as tc,ET as uc,CT as vc,RT as wc,vu as xc,TT as yc,db as zc,OT as Ac};
2289
+ //# sourceMappingURL=chunk-C4O5TZY3.js.map