@unbrained/pm-cli 2026.10.5 → 2026.10.6

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 (114) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +26 -1
  3. package/dist/cli/register-setup.js +1 -1
  4. package/dist/cli/runtime/projection-retry.js +1 -1
  5. package/dist/cli-bundle/bundle-manifest.json +158 -158
  6. package/dist/cli-bundle/chunks/{chunk-Z66DWDAU.js → chunk-25EW53VO.js} +39 -38
  7. package/dist/cli-bundle/chunks/{chunk-YVBRASXO.js → chunk-3CCVTV6Q.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-5MNOWZPN.js → chunk-3REXBTST.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-4WB55TBC.js +80 -0
  10. package/dist/cli-bundle/chunks/{chunk-OOLYASYJ.js → chunk-6STTPXOC.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-AJ7H6XUF.js → chunk-ATB4ZZBQ.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-N4YGSG6F.js → chunk-D4G43LBV.js} +38 -38
  13. package/dist/cli-bundle/chunks/{chunk-HRJ6G6ZG.js → chunk-K6D6DMRT.js} +28 -28
  14. package/dist/cli-bundle/chunks/chunk-KIRHWPZB.js +2 -0
  15. package/dist/cli-bundle/chunks/chunk-O67BH435.js +6 -0
  16. package/dist/cli-bundle/chunks/{chunk-3CYOBJUK.js → chunk-RJHLD64E.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-WFZ4UEOB.js → chunk-TUKO5NF7.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-VZ63DEVJ.js → chunk-XJD47LUH.js} +2 -2
  19. package/dist/cli-bundle/chunks/{register-list-query-75QXHIFH.js → register-list-query-53WYLNZT.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-mutation-YS54SCHG.js → register-mutation-34XXUBVI.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-6KHZQSYJ.js → register-operations-WANO6EIM.js} +2 -2
  22. package/dist/cli-bundle/chunks/register-setup-WT37UPBQ.js +2 -0
  23. package/dist/cli-bundle/focused-chunks/{chunk-GITOYRUW.js → chunk-6KFKQD2D.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-UDYRVBOZ.js → chunk-FOHRPFIT.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-DDRN42PB.js → chunk-GRQXL5G5.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-ABV67XCC.js → chunk-JZ4WGUVH.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-B5RSLVE6.js → chunk-NM3PM6O6.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-OT7HK7SG.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/{chunk-2CVX3KR3.js → chunk-PCLU34KB.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-5C3IDDW7.js → chunk-QQIE4L42.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-RPUNVKXK.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-LE4JUCRR.js → chunk-RXSVJPZ7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-SPN5QTZ3.js +30 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-CLDPTMQY.js → chunk-SUZJNPGB.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-YMU42COG.js → chunk-W4BG5HHS.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-C224METM.js → chunk-Y5HXFDTZ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-ECBOPEJE.js → chunk-ZK5SOOPC.js} +61 -61
  38. package/dist/cli-bundle/focused-chunks/chunk-ZQK2XUSS.js +12 -0
  39. package/dist/cli-bundle/main.js +21 -21
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +1 -1
  42. package/dist/cli-bundle/sdk-core.js +31 -30
  43. package/dist/cli-bundle/sdk-governance.js +1 -1
  44. package/dist/cli-bundle/sdk-graph.js +1 -1
  45. package/dist/cli-bundle/sdk-merge.js +42 -42
  46. package/dist/cli-bundle/sdk-query.js +1 -1
  47. package/dist/cli-bundle/sdk-runtime.js +1 -1
  48. package/dist/cli-bundle/sdk-testing.js +1 -1
  49. package/dist/cli-bundle/sdk.js +2 -2
  50. package/dist/core/extensions/extension-types.d.ts +2 -0
  51. package/dist/core/extensions/extension-types.js +1 -1
  52. package/dist/sdk/cli-bootstrap.d.ts +5 -1
  53. package/dist/sdk/cli-bootstrap.js +1 -1
  54. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  55. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  56. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  57. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  58. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  59. package/dist/sdk/extension/managed-state.d.ts +2 -0
  60. package/dist/sdk/extension/managed-state.js +1 -1
  61. package/dist/sdk/extension/managed-update-status.d.ts +3 -0
  62. package/dist/sdk/extension/managed-update-status.js +2 -0
  63. package/dist/sdk/extension/source-resolution.d.ts +2 -6
  64. package/dist/sdk/extension/source-resolution.js +1 -1
  65. package/dist/sdk/extension/update-check.d.ts +10 -0
  66. package/dist/sdk/extension/update-check.js +1 -1
  67. package/dist/sdk/extension-command-context.js +2 -1
  68. package/dist/sdk/extension.d.ts +4 -0
  69. package/dist/sdk/extension.js +1 -1
  70. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  71. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  72. package/dist/sdk/public-surface.json +1 -1
  73. package/dist/sdk/query/get.js +1 -1
  74. package/dist/sdk/read-output-contracts.js +1 -1
  75. package/dist/sdk/runtime-input.js +1 -1
  76. package/dist/sdk/test/execution.d.ts +2 -1
  77. package/dist/sdk/test/execution.js +3 -3
  78. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +36 -0
  79. package/docs/GET_READ_EVIDENCE.md +17 -1
  80. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  81. package/docs/PR_REVIEW_LOOP.md +21 -4
  82. package/docs/README.md +1 -0
  83. package/docs/RELEASING.md +18 -0
  84. package/docs/SDK_CONFIGURATION_SAFETY.md +123 -0
  85. package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
  86. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  87. package/marketplace.json +2 -2
  88. package/package.json +3 -3
  89. package/packages/pm-beads/package.json +1 -1
  90. package/packages/pm-calendar/package.json +1 -1
  91. package/packages/pm-command-kit/package.json +1 -1
  92. package/packages/pm-digital-twin/package.json +1 -1
  93. package/packages/pm-governance-audit/package.json +1 -1
  94. package/packages/pm-guide-shell/package.json +1 -1
  95. package/packages/pm-kanban/package.json +1 -1
  96. package/packages/pm-lifecycle-hooks/package.json +1 -1
  97. package/packages/pm-linked-test-adapters/package.json +1 -1
  98. package/packages/pm-search-advanced/package.json +1 -1
  99. package/packages/pm-templates/package.json +1 -1
  100. package/packages/pm-todos/package.json +1 -1
  101. package/packages/pm-vcs/package.json +1 -1
  102. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  103. package/plugins/pm-claude/package.json +2 -2
  104. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  105. package/plugins/pm-codex/package.json +2 -2
  106. package/plugins/pm-codex/plugin.json +1 -1
  107. package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +0 -80
  108. package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +0 -6
  109. package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +0 -2
  110. package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +0 -2
  111. package/dist/cli-bundle/focused-chunks/chunk-DOVTUKJQ.js +0 -2
  112. package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +0 -30
  113. package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +0 -12
  114. package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +0 -2
@@ -1,37 +1,38 @@
1
- import{n as yp,o as Ko,p as Sp,q as Ep,r as Ss,s as Bo,t as Ap,u as Es,v as Vo,y as Zp,z as eu}from"./focused-chunks/chunk-ABV67XCC.js";import{a as ou,f as au,h as en,m as iu,o as pr,r as ea,s as su,t as cu,x as lu}from"./focused-chunks/chunk-XV5RV4ZT.js";import{$ as Gn,$a as r_,A as Er,Ab as h_,B as hf,Bb as g_,C as Ta,Cb as y_,D as gf,Db as w_,E as yf,Eb as v_,Fb as Cr,Ga as Wf,Gb as cc,Hb as lc,Ia as Jf,Ib as Fa,J as wf,Ja as Pa,Jb as dc,K as vf,Ka as Sk,Kb as b_,L as bf,La as Xf,Lb as mc,M as kf,Ma as Qf,Mb as Ma,N as Sf,Na as sc,Nb as Kn,O as Ef,Ob as pc,P as Af,Pb as uc,Q as Tf,Qb as k_,R as Cf,Rb as S_,S as If,Sb as E_,T as Rf,Tb as zn,U as Of,Ub as fc,V as xf,Vb as A_,W as Pf,X as Nf,Y as Lf,Ya as e_,Yb as Da,Z as $f,Za as t_,_ as Ff,_a as n_,aa as Mf,ab as o_,ba as Df,bb as a_,ca as Uf,cb as i_,da as Dt,db as nn,dc as T_,ea as v,eb as s_,ec as C_,fa as Gf,fb as c_,fc as I_,g as lf,ga as jf,gb as Na,h as df,ha as Fe,hb as l_,ia as qf,ib as d_,ja as rc,jb as m_,jc as R_,ka as Kf,kb as p_,kc as U_,la as oc,lb as u_,ma as Ar,mb as La,na as Ca,nb as Ut,oa as jn,ob as f_,pa as zf,pb as $a,qa as Ia,ra as ge,sa as ac,sb as Tr,ta as _e,ua as Hf,va as Bf,wa as Ra,xa as Vf,y as _f,ya as Oa,z as ec,zb as __}from"./focused-chunks/chunk-ECBOPEJE.js";import{e as _p,g as hp,h as gp,k as wp,q as kp}from"./focused-chunks/chunk-CLDPTMQY.js";import{b as tu,c as Zo,e as nu,f as ru,g as ik}from"./focused-chunks/chunk-2CVX3KR3.js";import{R as Us,V as Qp,a as im,b as sm,c as cm,d as lm,f as dm}from"./focused-chunks/chunk-DOVTUKJQ.js";import{a as pf,b as uf,c as Ua}from"./focused-chunks/chunk-DDRN42PB.js";import{K as Zf,b as ff}from"./focused-chunks/chunk-UDYRVBOZ.js";import{Ba as wc,Da as F_,Sa as Or,Ua as M_,Va as D_,c as tc,e as nc,g as ic,h as Ir,i as Ek,j as _c,k as hc,l as Ga,m as Ak,n as Tk,pa as gc,s as O_,t as x_,u as P_,ua as Rr,v as N_,w as L_,wa as yc,x as $_}from"./focused-chunks/chunk-RHIH6XIW.js";import{$a as vr,A as ue,B as $n,C as _a,D as ha,G as ga,H as ya,I as Hu,Ia as Un,J as wa,Ja as nf,K as va,Ka as Qs,L as Fn,La as rf,M as Js,N as ba,O as Bu,Oa as Zs,P as Vu,Pa as of,Q as yr,Xa as Sa,_a as sf,a as Gu,b as ia,c as sa,cb as cf,d as ca,e as la,i as da,j as Pt,k as Nn,kb as ht,l as ma,m as Ln,mb as Sr,n as pa,nb as tn,o as de,p as ua,pb as mf,q as Ws,qb as xa,r as Ve,s as Ys,sa as tf,t as ju,u as Ie,vb as qn,w as ft,x as qu,y as fa,z as Nt}from"./focused-chunks/chunk-C224METM.js";import{c as pp,f as up,g as fp,i as qo,j as Rt,k as Tp,l as Cp,m as Ip}from"./focused-chunks/chunk-LE4JUCRR.js";import{a as mu,b as pu,c as uu}from"./focused-chunks/chunk-5C3IDDW7.js";import{$ as Dm,A as yo,Aa as op,B as ym,Ba as ap,C as wm,Ca as Io,D as vm,Da as ip,E as wo,Ea as sp,F as bm,Fa as cp,G as km,Ga as Ro,H as Sm,Ha as Oo,I as Em,Ia as xo,J as vo,Ja as Po,K as bo,Ka as dr,L as Am,La as lp,M as ko,Ma as No,Na as mr,O as Tm,Oa as Lo,P as cr,Pa as $o,Q as Cm,Qa as Fo,R as Im,Ra as Mo,S as Rm,Sa as dp,T as Om,Ta as Ct,U as xm,Ua as Do,V as Pm,Va as Uo,W as Nm,Wa as Go,X as Lm,Xa as jo,Y as $m,Z as Fm,_ as Mm,_a as mp,aa as Um,ab as It,ba as Gm,bb as N,ca as jm,d as vs,da as lr,e as mm,ea as qm,fa as Km,ga as So,h as fo,ha as Eo,i as bs,ia as zm,j as Xt,ja as Hm,ka as Bm,l as pm,la as Vm,ma as Wm,na as Ym,oa as Jm,pa as Xm,q as ks,ra as Qm,s as _o,sa as Zm,t as ho,ta as ep,u as go,ua as tp,v as um,va as np,w as fm,wa as rp,x as _m,xa as Ao,y as hm,ya as To,z as gm,za as Co}from"./focused-chunks/chunk-YMU42COG.js";import{$ as Su,$a as zu,A as bk,Aa as hr,Ab as I,B as kk,Bb as q,C as Pn,Cb as se,D as C,Db as Xu,Fb as fe,Gb as Qu,H as ut,Ha as Nu,Hb as ka,Ib as _t,Ja as Bs,Jb as Zu,Kb as ce,L as hu,Lb as ef,M as oa,Ma as Lu,N as gu,Na as aa,O as yu,Oa as ot,P as wu,Pb as af,Q as vu,Qa as $u,R as bu,Ra as Fu,T as te,Ta as Mu,U as Gs,Ua as Vs,V as oe,Va as Du,Vb as br,Wa as Uu,Wb as kr,X as js,Xa as A,Xb as Ea,Y as ku,Ya as $e,Yb as Mt,Z as Be,Za as Ce,_ as nt,_a as Ku,a as ta,aa as Eu,ab as Lt,b as sk,bc as Aa,c as ck,ca as Au,cb as Ke,d as lk,da as Tu,db as gr,e as dk,ea as qs,eb as Mn,fb as Wu,gb as Dn,ha as Ks,hb as Xs,ib as Yu,ja as Cu,k as na,ka as Iu,l as fu,la as Ru,m as _u,ma as Ou,n as xn,na as xu,o as ur,ob as wr,p as mk,q as pk,r as uk,ra as Le,s as fk,sa as xt,sc as Yf,t as _k,u as hk,ua as zs,v as gk,va as fr,vb as $t,w as yk,wa as _r,x as wk,xa as Hs,xb as Ft,y as ra,ya as rt,z as vk,za as Pu,zb as Ju}from"./focused-chunks/chunk-GITOYRUW.js";import{b as Tt,c as co,d as lo,g as mt,i as zo,j as pt,k as Ot,l as vp,n as $,o as Ho,p as tt,r as bp}from"./focused-chunks/chunk-B5RSLVE6.js";import{e as du}from"./focused-chunks/chunk-PSXFFQFT.js";import{$ as d,$a as lt,$b as Rp,Ab as ws,B as Ud,Bb as sr,Bc as Gp,C as Gd,Ce as Jp,D as jd,Dc as Is,Dd as Vb,E as qd,Ec as Rs,Ed as Wb,F as Kd,Fc as Os,G as zd,Gb as ke,Gc as xs,Gd as Yb,Ge as nk,H as ds,Ha as An,Hc as Ps,He as rk,I as ms,Ib as B,Ic as Ns,Id as Jb,Ie as ok,J as ps,Ja as Jd,Jc as Ls,Jd as Xb,Je as ak,K as us,Kb as Jt,Kc as O,Kd as Fs,Ke as Qo,L as fs,La as gs,Lc as In,Ld as Ms,Le as Xp,M as _s,Mc as Qt,Md as Ds,Nc as Y,Nd as zp,Oa as ys,Oc as Wo,P as so,Pa as rr,Pc as Rn,Pd as Hp,Qa as Ae,Qb as Cn,Qd as Qb,Sc as Yo,Sd as Zb,Ta as x,Td as ek,U as hs,Ua as be,Uc as Se,Ud as tk,Va as po,Vc as Jo,W as Hd,Wa as Tn,Wd as k,Xa as or,Ya as Xd,Yc as jp,Z as At,Za as E,Zc as Zt,_a as Qd,_d as Xo,aa as l,ab as re,ac as Op,ae as ie,bb as dt,bc as xp,cc as Pp,db as et,dc as Np,de as Te,eb as uo,ec as Lp,fc as As,gc as $p,ia as Bd,ib as Zd,ic as Fp,jb as em,jc as Mp,je as Bp,ka as Vd,kb as tm,lb as nm,ld as qp,ma as mo,mb as rm,mc as Ts,nb as om,nc as Dp,o as oo,oa as Wd,ob as am,oc as Cs,p as Dd,pa as Yd,pd as Kp,q as ao,qb as ar,qe as Vp,r as ls,rb as Yt,re as Wp,sa as j,sb as qe,ta as Wt,ua as He,ud as $s,ue as On,v as Vt,va as ee,vc as Up,w as ct,x as kn,xa as ne,y as Sn,ye as Yp,z as io,za as En,zb as ir}from"./focused-chunks/chunk-GUIF3WVC.js";import{AsyncLocalStorage as gM}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73dbe40e-f7a2-5aca-85aa-a5775e5e981a")}catch{}})();var Ck=Us("list").properties.outputSession,Ik={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...Ck},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},G_={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},j_={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},le={type:"string",description:"pm item id, for example pm-abc1."},Rk=`Operation name (one of): ${Cs.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,Ok={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},xk={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function D(e,t=[]){return{...j_,properties:{...j_.properties,...e},required:t}}var Pk=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:D({action:{type:"string",enum:[...Cs],description:Rk},id:le,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...Ik},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:D({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:D({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:D({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({query:{type:"string"},options:{type:"object"},...xk},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({options:{type:"object"},...Ok})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:D({id:le,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:D({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:D({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:le,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:D({id:le,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:D({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:le,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:D({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:le,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:D({subcommand:{type:"string",enum:[...$p]},id:le,target:le,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:D({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:D({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:D({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:D({...G_,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Cn],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...ls]},description:`Lifecycle roles for add-status: ${ls.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:G_}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:D({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:D({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:D({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],Nk={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},Lk=Pk.map(e=>{let t=Nk[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Us(t,{properties:n,required:r})}});function q_(){return Lk.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48a78171-1f14-5e93-82a2-27108ee87f4f")}catch{}})();var K_=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),$k=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Z_=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),qa=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),rn=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),eh=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),th=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),nh=new Map([...th.entries()].flatMap(([e,t])=>gt(t).map(n=>[n,e]))),rh=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],kc=new Map(rh.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),Fk=10,Mk=20,z_=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),oh=[["init",Tm],["install",Im],["uninstall",Rm],["explore",Om],["manage",Fm],["describe",xm],["reload",Mm],["doctor",Dm],["catalog",Um],["adopt",Gm],["adopt-all",Pm],["activate",Nm],["deactivate",Lm],["migrate",$m]],Dk=[...oh.map(([e,t])=>e==="init"?[e,Cm]:[e,t]),["upgrade",lr]],Uk=[...oh.map(([e,t])=>[`extension ${e}`,t]),...Dk.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",bo],["config",Am],["extension",ko],["package",cr],["packages",cr],["install",jm],["create",Io],["item mutate",ip],["item complete",sp],["item reopen",cp],["copy",Ro],["focus",Oo],["update",xo],["update-many",Po],["upgrade",lr],["calendar",dr],["cal",dr],["context",mr],["ctx",mr],["get",Lo],["search",Uo],["eval",dp],["events",No],["workspace",Ct],["workspace position",[]],["workspace snapshot",Ct],["workspace snapshot create",Ct],["workspace snapshot list",Ct],["workspace snapshot inspect",Ct],["workspace snapshot restore",Ct],["workspace snapshot delete",Ct],["next",Do],["aggregate",go],["deps",Fo],["graph",Mo],["guide",$o],["reindex",qm],["history",yo],["history-compact",bm],["history-attest",km],["history-redact",wm],["history-repair",vm],["history-author-acknowledge",wo],["merge",ym],["schema",Sm],["profile",Em],["plan",vo],["restore",Hm],["delete",Bm],["close",Km],["close-many",So],["append",Eo],["claim",zm],["release",Vm],["start-task",Wm],["pause-task",Ym],["close-task",Jm],["comments",um],["notes",fm],["learnings",_m],["files",hm],["docs",gm],["test",Zm],["test-runs-worker",[]],["test-all",ep],["telemetry",tp],["test-runs",np],["gc",rp],["stats",Ao],["ops",[]],["duplicates",To],["validate",op],["health",Co],["assurance",ap],...mp,["contracts",Go],["completion",jo],["activity",lp],...[...Z_].map(e=>[e,ho])],xr=new Map(Uk);for(let{alias:e,canonical:t}of ke){let n=xr.get(e);n!==void 0&&xr.set(t,n)}function Gk(e){return nh.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function H_(e){let t=ke.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:As.includes(e)?ye(e):e.startsWith("extension-")?ye(`extension ${e.slice(10)}`):e.startsWith("package-")?ye(`package ${e.slice(8)}`):e.startsWith("item-")?ye(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ye(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ye(`templates ${e.slice(10)}`):qa.has(e)?th.get(e)??ye(e):null}function jk(e,t){let n=B(t);return n!==t||ke.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:gt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function gt(e){return e.split("|").map(t=>ye(t)).filter(t=>t.length>0)}function qk(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let a of gt(o.command_path)){let i=a.split(" ").filter(s=>s.length>0);if(i.length!==0)for(let s=i.length;s>0;s-=1){let c=i.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,a)=>o.localeCompare(a))}function ja(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Pr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function Kk(e,t){if(!t)return{...e};let n=Pr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let a=o.action;return typeof a!="object"||a===null?!1:a.const===t});return{...e,oneOf:n}}function vc(e,t){let n=Pr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let a=o.action;if(typeof a!="object"||a===null)return!1;let i=a.const;return typeof i=="string"&&t.has(i)});return{...e,oneOf:n}}function ye(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ah(e){return e.replace(/\s+/g,"-")}function at(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function B_(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=at(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function bc(e,t,n){n&&(e[t]=!0)}function V_(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function zk(e){let t=V_(e.long,"long"),n=V_(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),bc(o,"required",e.required===!0),bc(o,"repeatable",e.repeatable===!0),bc(o,"list",e.list===!0);let a=at(e.description);a&&(o.description=a);let i=at(e.value_name);i&&(o.value_name=i);let s=[at(e.value_type),at(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return s&&(o.value_type=s),o}function ih(e){let t=new Map;for(let r of e){let o=ye(r.target_command);if(o.length===0)continue;let a=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;a.sourceDedupe.has(i)||(a.sourceDedupe.add(i),a.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=zk(s);if(!c)continue;let m=`${c.flag}|${c.short??""}`;a.dedupe.has(m)||(a.dedupe.add(m),a.flags.push(c))}t.set(o,a)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((a,i)=>{let s=a.layer.localeCompare(i.layer);return s!==0?s:(a.name??"").localeCompare(i.name??"")})});return n}function Hk(e){let t=ih(e.flagRegistrations),n=new Map;for(let a of e.commandDefinitions){let i=ye(a.command);if(i.length===0)continue;let s=at(a.action)??ah(i),c=Array.isArray(a.arguments)?a.arguments.map(m=>{let p=at(m.name);return p?{name:p,required:m.required===!0,variadic:m.variadic===!0,description:at(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{...a.tier===void 0?{}:{tier:a.tier},command:i,action:s,source:{layer:a.layer,name:a.name},description:at(a.description),intent:at(a.intent),arguments:c,flags:t.get(i)?.flags??[],examples:B_(a.examples),failure_hints:B_(a.failure_hints)})}let r=new Set;for(let a of e.handlers)r.add(ye(a));for(let a of n.keys())r.add(a);for(let a of t.keys())r.add(a);let o=[];for(let a of[...r].sort((i,s)=>i.localeCompare(s))){let i=n.get(a);o.push(Bk(a,i,t.get(a)?.flags??[]))}return o}function Bk(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:ah(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Vk(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let n=t.replace(/-([a-z0-9])/g,(r,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return n.length>0?n:null}function Wk(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function Yk(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function Jk(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=Wk(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let a=Vk(o);!a||n[a]!==void 0||(n[a]=Yk(o,e.action),o.required===!0&&r.push(a))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Xk(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function Qk(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((a,i)=>a.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(a=>`${a.flag}|${a.short??""}`));for(let a of n.flags){let i=`${a.flag}|${a.short??""}`;if(!o.has(i))o.add(i),r.flags.push(a);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);s&&Xk(s,a)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function Zk(e,t=A){let n={mode:At.extensions.policy.mode,trust_mode:At.extensions.policy.trust_mode,default_sandbox_profile:At.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await j(re(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),a=await ir({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await sr({...a,loaded:a.loaded});return{handlers:new Set(i.commands.handlers.map(s=>ye(s.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:a.policy.mode,trust_mode:a.policy.trust_mode,default_sandbox_profile:a.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function eS(e,t={}){let n=new Map;for(let r of Ts){let o=qa.has(r);if(o&&!t.includePackageOwnedActions)continue;let a=H_(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:a})}if(t.includePackageOwnedActions)for(let r of qa)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:H_(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ke.find(o=>o.alias===r.command)?.canonical??ye(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function tS(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!rn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?gt(e.command_path):[],r=n.some(i=>t.handlers.has(i)||t.handlers.has(B(i))),o=n.map(i=>eh.get(B(i))).find(i=>typeof i=="string"),a=t.disabledReason===null&&r;return{action:e.action,invocable:a,available:a,requires_extension:!0,provider:"extension",disabled_reason:a?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function sh(e){return xr.get(e)??_o}function nS(e){return rn.has(B(e))?!1:xr.has(e)}function rS(e){return Z_.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function W_(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function oS(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function aS(e){let t=new Map;for(let r of e.definitions){let o=W_(r.cli_flag);if(!o)continue;let a=r.cli_aliases.map(s=>oS(s)).find(s=>s!==null),i=r.cli_aliases.map(s=>W_(s)).filter(s=>s!==null&&s!==o);for(let s of r.commands){let c=t.get(s)??{flags:[],seen:new Set},m=a?{flag:o,short:a}:{flag:o},p=`${m.flag}|${m.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(m));for(let u of i){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(s,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,ks(o.flags));return n}function Y_(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let a=`${o.flag}|${o.short??""}`;r.has(a)||(r.add(a),n.push(o))}return ks(n)}function iS(e,t,n,r,o){let a=new Map(t);for(let{alias:i,canonical:s}of ke){let c=t.get(s)??t.get(i);c&&(a.set(i,c),a.set(s,c))}return e.map(i=>{let s=nS(i),c=s?sh(i):[],m=n.get(rS(i))??[],p=a.get(i),u=Y_(c,m),f=Y_(u,p?.flags??[]),_=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:i,flags:f,...r?{canonical_command:lh(i),visibility:ch(i,o),positionals:mm(i)?.slots??[],flag_invocations:pr(i,f)}:{},provider:_,extension_sources:p?.sources}}).sort((i,s)=>i.command.localeCompare(s.command))}function sS(e,t=Jt){let n=new Set(e),r=new Map;for(let o of rh){let a=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:a,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let a=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};a.aliases.includes(o.alias)||a.aliases.push(o.alias),a.contracts.push(o),r.set(o.canonical,a)}return[...r.values()].map(({contracts:o,...a})=>o.length===0?a:{...a,contracts:o}).sort((o,a)=>o.canonical.localeCompare(a.canonical))}function cS(){return{create_string_options:tu,create_repeatable_options:Zo,update_string_options:nu,update_repeatable_options:ru,list_string_options:im,search_string_options:sm,calendar_string_options:cm,context_string_options:lm,activity_string_options:dm}}function J_(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let s of e.required_create_fields)n.add(s);for(let s of e.required_create_repeatables)n.add(s)}let r=Tn(e,"create",n),o=[...new Set(r.required)].sort((s,c)=>s.localeCompare(c)),a=[...new Set(o.map(s=>Ae("create",s)))].sort((s,c)=>s.localeCompare(c)),i=[...new Set(e.options.filter(s=>s.required===!0).map(s=>s.key))].sort((s,c)=>s.localeCompare(c));return{required_option_keys:o,required_flags:a,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function lS(e){let t={},n={};for(let r of[...e.types].sort((o,a)=>o.localeCompare(a))){let o=e.by_type[r];t[r]=J_(o,"strict"),n[r]=J_(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function dS(e,t){let n=Pr(e);if(n.length===0)return e;let r=!1,o=n.map(a=>{let i=a.properties;if(typeof i!="object"||i===null)return a;let s=i.action;return typeof s!="object"||s===null||s.const!=="create"?a:(r=!0,{...a,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function mS(e){let t=ja(e.action)!==void 0||ja(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,a=e.flagsOnly===!0,i=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,m=ja(e.action),p=ja(e.command),u=!r&&!c&&!o&&!a&&!i&&!m&&!p;return{selectedAction:m,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:a,availabilityOnly:i,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function pS(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function uS(e,t=A){try{return await t(e)}catch{return structuredClone(At)}}async function fS(e,t,n){let r=await uS(t),o=await Zk(e),a=x(r,o.registrations??O()),i=tt(r.schema),s=Hk(o);return{settings:r,runtimeProbe:o,typeRegistry:a,statusRegistry:$(r.schema),runtimeFieldRegistry:i,runtimeFieldFlagMap:aS(i),createRequiredOptionContracts:lS(a),extensionContracts:s,mergedExtensionContracts:Qk(s.filter(c=>Ka(n,c.command,s))),extensionFlagMap:ih(o.flagRegistrations)}}function X_(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&qa.has(e.selectedAction)||e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand)))}function _S(e,t){let n=eS(t,{includePackageOwnedActions:X_(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Dp);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(a=>a.action===o.action)?.tier??ea(o.action))!=="internal"))}return X_(e)&&e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:Gk(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function hS(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function gS(e,t){return[...new Set([...As.filter(n=>!rn.has(B(n))),...[...xr.keys()].filter(n=>!rn.has(B(n))),...e.flatMap(n=>n.command_path?gt(n.command_path).filter(r=>n.provider==="extension"||!rn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=ke.find(a=>a.alias===r||a.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>ye(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function yS(e,t){let n=t.slice(0,Fk),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),a=t.slice(0,Mk),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),s=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,d.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:i,nextSteps:[`Retry with a child command, for example: ${i[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:a.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function wS(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function vS(e){return new l(`Unknown command: "${e}".`,d.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function bS(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(n.length>0)throw yS(e.selectedCommand,n);let r=eh.get(B(e.selectedCommand));throw r?wS(e.selectedCommand,r):vS(e.selectedCommand)}function kS(e,t){let n=_S(e,t.mergedExtensionContracts);hS(e,n);let r=gS(n,t.mergedExtensionContracts);bS(e,r);let o=e.selectedCommand?nh.get(B(e.selectedCommand)):void 0,a=e.selectedCommand?n.filter(m=>o?m.action===o:jk(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!a.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let i=e.selectedAction?a.filter(m=>m.action===e.selectedAction):a,s=[...new Map(i.map(m=>tS(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?s.filter(m=>m.invocable):s;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:a,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function SS(e){return new Set(Pr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function ES(e){let t=Qp,n=Pr(t),r=SS(t),o=e.filter(a=>!r.has(a.action)).map(a=>Jk(a));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Q_(e,t,n){let r=new Set(t.actionDescriptors.map(a=>a.action)),o=e.selectedAction?Kk(n,e.selectedAction):e.selectedCommand?vc(n,new Set(t.scopedActionDescriptors.map(a=>a.action))):vc(n,r);return e.runtimeOnly&&!e.selectedAction?vc(o,new Set(t.actions)):o}function AS(e,t,n){let r=ES(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?dS(Q_(e,n,r),t.createRequiredOptionContracts):Q_(e,n,r);return{mergedSchema:r,filteredSchema:o}}function TS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?qk(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function ch(e,t){return t.find(n=>B(n.command)===B(e))?.tier??ea(e)}function Ka(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||ch(t,n)!=="internal"}function CS(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Jt.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of kc.keys())r.add(o);return t.filter(o=>!r.has(o)&&Ka(e,o,n))}function lh(e){let t=ke.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":kc.get(n)??n}var IS=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),RS=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function OS(e,t){let n=z_.get(B(e))??(e.includes(" ")?void 0:z_.get(lh(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>gt(m.command).some(p=>B(p)===B(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),a=o.at(-1),i=o.slice(0,-1).join(" "),s=IS.get(a),c=RS.get(e)??i;return{intent:s===void 0||i.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function xS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ye))].filter(a=>a.length>0).sort((a,i)=>a.localeCompare(i)).map(a=>{let i=$s(a,{generateFallback:!0}),s=a.split(" ")[0],c=kc.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),m=new Set([...sh(a).map(f=>f.flag),...t.filter(f=>gt(f.command).some(_=>B(_)===B(a))).flatMap(f=>f.flags.map(_=>_.flag))]),p=(K_.get(B(a))??K_.get(c)??$k).filter(f=>m.has(f)),u=OS(a,t);return{command:a,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function PS(e){return e.map(t=>({budget:$s(t,{generateFallback:!0}),envelope:lu(t)}))}function NS(e){let t=new Map;for(let n of e){let r=au(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,a=o.join(","),i=t.get(a)??{commands:[],exit_codes:o};i.commands.push(n),t.set(a,i)}return[...t.values()]}function LS(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>gt(r.command).some(o=>B(o)===B(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>gt(o.command).some(a=>r.has(a)))}return t.extensionContracts.filter(r=>Ka(e,r.command,t.extensionContracts))}function $S(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function FS(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=du);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,a])=>[o,[...new Set(a.map(i=>`--${i.cli_flag}`))].sort((i,s)=>i.localeCompare(s))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Rp],services:[...Op],policy_modes:[...xp],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Lp],trust_modes:[...Pp],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Np],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Ud],create_modes:[...Gd],close_validation_modes:[...jd],workflow_enforcement_modes:[...qd]},e.relationship_kind_contracts=[...Bd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,a)=>o.kind.localeCompare(a.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function MS(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function DS(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=iS(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let a=new Set(r);e.list_projections=Object.entries(uu).filter(([i])=>a.has(i)).map(([i,s])=>({command:i,default:s,brief_fields:[...pu],compact_fields:[...mu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:a,aliases:i})=>({canonical:a,aliases:i})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function US(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=cS();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function GS(e,t,n,r){e.command_summaries=xS(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...qp],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(ye))].filter(o=>Ms(o)!==void 0).sort((o,a)=>o.localeCompare(a)).map(o=>({command:o,modes:[...zp(o).keys()]}))}:{}},e.grammar_contracts={nouns:Xt.nouns,shared_verbs:Xt.shared_verbs,scope_before_verb:Xt.scope_before_verb,visible_top_level_ceiling:Xt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Xt.ceiling_raise_requires_pm_item,positional_shape_budget:Xt.positional_shape_budget,positional_shape_count:new Set(bs.map(({slots:o})=>pm(o))).size,positional_action_count:vs.length,positional_action_parents:[...new Set(vs.map(({parent:o})=>o))].sort((o,a)=>o.localeCompare(a)),...r.includePositionalSignatures?{positional_signatures:bs}:{}}}async function Sc(e,t){let n=mS(e);pS(n);let r=E(process.cwd(),t.path),o=await fS(t,r,n),a=kS(n,o),i=AS(n,o,a),s=TS(n,a),c=CS(n,s,o.extensionContracts),m=$S(n,i,a,c),p=LS(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&GS(m,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return m;let f=sS(a.commandCatalog.filter(_=>Ka(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||FS(m,o,n),MS(m,n,i,p),DS(m,n,o,c,f),US(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...df],gate_triggers:[...lf]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=fo.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=q_(),m.context_intents=Vp(),m.read_output_dimensions=Fs,m.error_codes=iu,m.command_output_contracts=PS(c),m.diagnostic_output_contracts=Kp,m.command_exit_contracts={vocabulary:ou,command_sets:NS(c)}),m}import{readFile as jS}from"node:fs/promises";import qS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();var Ec="context-intents.json";function za(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function KS(e,t,n){if(!za(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="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:r,token_budget:e.token_budget}}function dh(e,t){let n=Array.isArray(e)?e:za(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((r,o)=>KS(r,t,o))}async function zS(e){let t=qS.join(e,Ec),n;try{n=await jS(t,"utf8")}catch(o){if(Wt(o))return[];throw await Ju(e),o}let r;try{r=JSON.parse(n)}catch(o){let a=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Ec}: ${a}`,{cause:o})}return dh(r,Ec)}function HS(e){if(!za(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return za(n)?n.contextIntents??n.context_intents:void 0}function BS(e){return e.flatMap(t=>{let n=HS(t.module);return n===void 0?[]:dh(n,`package ${t.name}`)})}async function VS(e){let t=await zS(e.pmRoot),n=BS(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Ac(e,t){let n=await VS(e);return await Wp(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();async function mh(e,t,n=Bp){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(a=>typeof a=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as YS}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c08374a3-4ac6-5f9a-be69-0ac9839bba39")}catch{}})();var Tc="PmCliError";function WS(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function ph(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,WS(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Ha(e){if(!(e instanceof Error)||e.name!==Tc)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8f2f0b4-4679-55d2-9336-9f9b9d38067f")}catch{}})();function Cc(e){let t=Vd();for(let n of e)t.register(n);return t}function uh(e,t,n,r){return{client:t,isItemNotFoundError:o=>Ha(o)&&o.exitCode===d.NOT_FOUND,getItemAt:(o,a)=>mf(o,a,{pmRoot:e}),openRelationshipEventStore:o=>uf.open({pmRoot:e,nodes:o.nodes,registry:Cc(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Yd(o.nodes,o.edges,Cc(o.definitions)),analyzeRelationshipImpact:(o,a,i)=>ff(o,a,i),validateRelationshipEvents:o=>{let a=new pf(o.nodes,{registry:Cc(o.definitions)});return o.events.map(i=>a.append({...i,expectedVersion:a.version}))},commitWorkspaceTransaction:o=>_f({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new l("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",d.USAGE);let a=o.dryRun===!0?await Fu(e,()=>A(e)):await A(e);try{let i=await aa({pmRoot:e,filePath:re(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${YS("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:n??C(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async s=>{let c=s===null?null:JSON.parse(s),m=ta(c);if(!m.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",d.USAGE);let p=Vs(m.data),u=await o.mutate(structuredClone(p));if(!ta(u).success)throw new l("Workspace settings mutation returned invalid settings.json.",d.USAGE);let f=qe(p,u)?s:Du(u,{source:{raw:c,validated:m.data}}),_=ta(JSON.parse(f));if(!_.success)throw new l("Workspace settings mutation serialized invalid settings.json.",d.USAGE);return{raw:f,result:o.includePreview===!0?Vs(_.data):void 0}}});return i.changed&&o.dryRun!==!0&&await Y({path:re(e),scope:"project",op:"extension:pm:settings"}),{changed:i.changed,dry_run:o.dryRun===!0,replayed:i.replayed===!0,...i.result===void 0?{}:{preview:i.result}}}finally{$u(e)}}}}import JS from"node:fs/promises";import X from"node:path";import XS from"node:readline/promises";import{stdin as QS,stdout as Me}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="95053097-fc76-5587-ab41-8cb05b9d3cd9")}catch{}})();var Rc=Symbol.for("pm.sdk.init-invocation-cwd");var ZS=()=>XS.createInterface({input:QS,output:Me});function eE(){return structuredClone(At)}var tE=["minimal","default","strict"];function _h(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${tE.join(", ")}`,d.USAGE)}function nE(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return hp(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${_p.join(", ")}`,d.USAGE)}}}function rE(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function Ic(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:X.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function oE(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||Ic(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=X.resolve(e,o),p=X.join(m,".agents","pm");return{pmRoot:p,prefixArg:n,target:{mode:"workspace-path",tracker_root:p,workspace_root:m}}}if(t.path===void 0&&Ic(n)){let m=X.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let a=E(e,t.path),i=X.join(X.resolve(e),".agents","pm"),s=X.dirname(X.dirname(a)),c=X.resolve(a)===i?"current":"ancestor";return{pmRoot:a,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:a,workspace_root:s,discovery:c,requested_cwd:X.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:a}}}function aE(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(Ic(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Lt(e)!==Lt(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Lt(e)}`,`pm init --id-prefix ${Lt(t)}`]});return t}function iE(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${Mf.join(", ")}`,d.USAGE)}function sE(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function hh(e,t){let n=Hd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function cE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lE(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(cE).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function dE(e,t,n){let r=zo(t.schema),o=pt(e,r.files.types,mt.types),a=up(await ee(o)),i=[],s=[];for(let c of gp(n)){let m=fp(a,c);a=m.file,(m.replaced?s:i).push(m.definition.name)}return await ot({pmRoot:e,filePath:o,raw:qo(a),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:i,updated:s,file:o}}async function mE(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",X.join(".agents","pm")];for(let n of t)if(await j(X.join(e,n)))return!0;return!1}async function pE(e,t,n){if(!t||n||await j(X.join(e,"settings.json"))||!await mE(e))return;let r=X.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function gh(e,t){let n=[],r=[];for(let o of t){let a=o?X.join(e,o):e,i=await j(a);await JS.mkdir(a,{recursive:!0}),i?r.push(`already_exists:${a}`):n.push(a),r.push(...await Y({path:a,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function uE(e,t){let n=ZS();try{Me.write(`pm init setup wizard (agent-optimized)
2
- `),Me.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
1
+ import{n as wp,o as Ko,p as Ep,q as Ap,r as Es,s as Bo,t as Tp,u as As,v as Vo,y as eu,z as tu}from"./focused-chunks/chunk-JZ4WGUVH.js";import{a as au,f as iu,h as en,m as su,o as mr,r as ea,s as cu,t as lu,x as du}from"./focused-chunks/chunk-RPUNVKXK.js";import{$ as Gn,$a as a_,A as Sr,Ab as y_,B as yf,Bb as w_,C as Ca,Cb as v_,D as wf,Db as b_,E as vf,Eb as k_,Fb as Tr,Ga as Jf,Gb as dc,Hb as mc,Ia as Qf,Ib as Ma,J as bf,Ja as Na,Jb as pc,K as kf,Ka as Ek,Kb as S_,L as Sf,La as Zf,Lb as uc,M as Ef,Ma as e_,Mb as Da,N as Af,Na as lc,Nb as Kn,O as Tf,Ob as fc,P as Cf,Pb as _c,Q as If,Qb as E_,R as Rf,Rb as A_,S as Of,Sb as T_,T as xf,Tb as zn,U as Pf,Ub as hc,V as Nf,Vb as C_,W as Lf,X as $f,Y as Ff,Ya as n_,Yb as Ua,Z as Mf,Za as r_,_ as Df,_a as o_,aa as Uf,ab as i_,ba as Gf,bb as s_,ca as jf,cb as c_,da as Dt,db as nn,dc as I_,ea as v,eb as l_,ec as R_,fa as qf,fb as d_,fc as O_,g as lf,ga as Kf,gb as La,h as df,ha as Me,hb as m_,ia as zf,ib as p_,ja as ac,jb as u_,jc as x_,ka as Hf,kb as f_,kc as j_,la as ic,lb as __,ma as Er,mb as $a,na as Ia,nb as Ut,oa as jn,ob as h_,pa as Bf,pb as Fa,qa as Ra,ra as ge,sa as sc,sb as Ar,ta as _e,ua as Vf,va as Wf,wa as Oa,xa as Yf,y as gf,ya as xa,z as nc,zb as g_}from"./focused-chunks/chunk-ZK5SOOPC.js";import{e as hp,g as gp,h as yp,k as vp,q as Sp}from"./focused-chunks/chunk-SUZJNPGB.js";import{b as nu,c as Zo,e as ru,f as ou,g as sk}from"./focused-chunks/chunk-PCLU34KB.js";import{R as Gs,V as Zp,a as sm,b as cm,c as lm,d as dm,f as mm}from"./focused-chunks/chunk-OT7HK7SG.js";import{a as ff,b as _f,c as Ga}from"./focused-chunks/chunk-GRQXL5G5.js";import{K as t_,b as hf}from"./focused-chunks/chunk-FOHRPFIT.js";import{A as M_,Ea as bc,Ga as D_,Va as Rr,Xa as U_,Ya as G_,a as mf,b as pf,c as Ta,f as rc,h as oc,j as cc,k as Cr,l as Ak,m as gc,n as yc,o as ja,p as Tk,q as Ck,sa as wc,v as P_,w as N_,x as L_,xa as Ir,y as $_,z as F_,za as vc}from"./focused-chunks/chunk-ZQK2XUSS.js";import{$a as wr,A as ue,B as $n,C as _a,D as ha,G as ga,H as ya,I as Hu,Ia as Un,J as wa,Ja as nf,K as va,Ka as ec,L as Fn,La as rf,M as Qs,N as ba,O as Bu,Oa as tc,P as Vu,Pa as of,Q as gr,Xa as Sa,_a as sf,a as Gu,b as ia,c as sa,cb as cf,d as ca,e as la,i as da,j as Pt,k as Nn,kb as ht,l as ma,m as Ln,mb as kr,n as pa,nb as tn,o as de,p as ua,pb as uf,q as Js,qb as Pa,r as We,s as Xs,sa as tf,t as ju,u as Ie,vb as qn,w as ft,x as qu,y as fa,z as Nt}from"./focused-chunks/chunk-Y5HXFDTZ.js";import{c as up,f as fp,g as _p,i as qo,j as Rt,k as Cp,l as Ip,m as Rp}from"./focused-chunks/chunk-RXSVJPZ7.js";import{a as pu,b as uu,c as fu}from"./focused-chunks/chunk-QQIE4L42.js";import{$ as Um,A as yo,Aa as ap,B as wm,Ba as ip,C as vm,Ca as Io,D as bm,Da as sp,E as wo,Ea as cp,F as km,Fa as lp,G as Sm,Ga as Ro,H as Em,Ha as Oo,I as Am,Ia as xo,J as vo,Ja as Po,K as bo,Ka as lr,L as Tm,La as dp,M as ko,Ma as No,Na as dr,O as Cm,Oa as Lo,P as sr,Pa as $o,Q as Im,Qa as Fo,R as Rm,Ra as Mo,S as Om,Sa as mp,T as xm,Ta as Ct,U as Pm,Ua as Do,V as Nm,Va as Uo,W as Lm,Wa as Go,X as $m,Xa as jo,Y as Fm,Z as Mm,_ as Dm,_a as pp,aa as Gm,ab as It,ba as jm,bb as N,ca as qm,d as bs,da as cr,e as pm,ea as Km,fa as zm,ga as So,h as fo,ha as Eo,i as ks,ia as Hm,j as Xt,ja as Bm,ka as Vm,l as um,la as Wm,ma as Ym,na as Jm,oa as Xm,pa as Qm,q as Ss,ra as Zm,s as _o,sa as ep,t as ho,ta as tp,u as go,ua as np,v as fm,va as rp,w as _m,wa as op,x as hm,xa as Ao,y as gm,ya as To,z as ym,za as Co}from"./focused-chunks/chunk-W4BG5HHS.js";import{$ as Eu,$a as zu,A as kk,Aa as _r,Ab as I,B as Sk,Bb as q,C as Pn,Cb as se,D as C,Db as Xu,Fb as fe,Gb as Qu,H as ut,Ha as Lu,Hb as ka,Ib as _t,Ja as Vs,Jb as Zu,Kb as ce,L as gu,Lb as ef,M as oa,Ma as $u,N as yu,Na as aa,O as wu,Oa as Ve,P as vu,Pb as af,Q as bu,Qa as Fu,R as ku,Ra as Mu,T as te,Ta as Du,U as js,Ua as Ws,V as oe,Va as Ys,Vb as vr,Wa as Uu,Wb as br,X as qs,Xa as A,Xb as Ea,Y as Su,Ya as Fe,Yb as Mt,Z as Be,Za as Ce,_ as rt,_a as Ku,a as ta,aa as Au,ab as Lt,b as ck,bc as Aa,c as lk,ca as Tu,cb as Ke,d as dk,da as Cu,db as hr,e as mk,ea as Ks,eb as Mn,fb as Wu,gb as Dn,ha as zs,hb as Zs,ib as Yu,ja as Iu,k as na,ka as Ru,l as _u,la as Ou,m as hu,ma as xu,n as xn,na as Pu,o as pr,ob as yr,p as pk,q as uk,r as fk,ra as $e,s as _k,sa as xt,sc as Xf,t as hk,u as gk,ua as Hs,v as yk,va as ur,vb as $t,w as wk,wa as fr,x as vk,xa as Bs,xb as Ft,y as ra,ya as ot,z as bk,za as Nu,zb as Ju}from"./focused-chunks/chunk-6KFKQD2D.js";import{b as Tt,c as co,d as lo,g as mt,i as zo,j as pt,k as Ot,l as bp,n as $,o as Ho,p as nt,r as kp}from"./focused-chunks/chunk-NM3PM6O6.js";import{e as mu}from"./focused-chunks/chunk-PSXFFQFT.js";import{$ as d,$a as Zd,$d as Xo,Ab as ar,B as Gd,Bb as vs,C as jd,Cb as ir,Cc as jp,D as qd,De as Xp,E as Kd,Ec as Rs,Ed as Wb,F as zd,Fc as Os,Fd as Yb,G as Hd,Gc as xs,H as ds,Ha as An,Hb as ke,Hc as Ps,Hd as Jb,He as rk,I as ms,Ic as Ns,Ie as ok,J as ps,Ja as Xd,Jb as B,Jc as Ls,Jd as Xb,Je as ak,K as us,Kc as $s,Kd as Qb,Ke as ik,L as fs,La as gs,Lb as Jt,Lc as O,Ld as Ms,Le as Qo,M as _s,Ma as ys,Mc as In,Md as Ds,Me as Qp,Nc as Qt,Nd as Us,Oc as Y,Od as Hp,P as so,Pa as ws,Pc as Wo,Qa as nr,Qc as Rn,Qd as Bp,Ra as Ae,Rb as Cn,Rd as Zb,Tc as Yo,Td as ek,U as hs,Ua as x,Ud as tk,Va as be,Vc as Se,Vd as nk,W as Bd,Wa as po,Wc as Jo,Xa as Tn,Xd as k,Ya as rr,Z as At,Za as Qd,Zc as qp,_a as E,_c as Zt,aa as l,ab as lt,ac as Op,bb as re,bc as xp,be as ie,cb as dt,cc as Pp,dc as Np,eb as tt,ec as Lp,ee as Te,fb as uo,fc as $p,gc as Ts,hc as Fp,ia as Vd,jb as em,jc as Mp,ka as Wd,kb as tm,kc as Dp,ke as Vp,lb as nm,ma as mo,mb as rm,md as Kp,nb as om,nc as Cs,o as oo,oa as Yd,ob as am,oc as Up,p as Ud,pa as Jd,pb as im,pc as Is,q as ao,qd as zp,r as ls,rb as or,re as Wp,sa as j,sb as Yt,se as Yp,ta as Wt,tb as Le,ua as He,v as Vt,va as X,vd as Fs,ve as On,w as ct,wc as Gp,x as kn,xa as ne,y as Sn,z as io,za as En,ze as Jp}from"./focused-chunks/chunk-SPN5QTZ3.js";import{AsyncLocalStorage as yM}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73dbe40e-f7a2-5aca-85aa-a5775e5e981a")}catch{}})();var Ik=Gs("list").properties.outputSession,Rk={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...Ik},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},q_={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},K_={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},le={type:"string",description:"pm item id, for example pm-abc1."},Ok=`Operation name (one of): ${Is.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,xk={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},Pk={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function D(e,t=[]){return{...K_,properties:{...K_.properties,...e},required:t}}var Nk=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:D({action:{type:"string",enum:[...Is],description:Ok},id:le,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...Rk},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:D({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:D({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:D({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({query:{type:"string"},options:{type:"object"},...Pk},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:D({options:{type:"object"},...xk})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:D({id:le,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:D({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:D({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:le,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:D({id:le,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:D({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:le,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:D({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:D({id:le,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:D({subcommand:{type:"string",enum:[...Fp]},id:le,target:le,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:le,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:D({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:D({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:D({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:D({...q_,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Cn],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...ls]},description:`Lifecycle roles for add-status: ${ls.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:q_}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:D({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:D({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:D({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],Lk={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},$k=Nk.map(e=>{let t=Lk[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Gs(t,{properties:n,required:r})}});function z_(){return $k.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48a78171-1f14-5e93-82a2-27108ee87f4f")}catch{}})();var H_=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),Fk=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],th=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Ka=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),rn=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),nh=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),rh=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),oh=new Map([...rh.entries()].flatMap(([e,t])=>gt(t).map(n=>[n,e]))),ah=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Ec=new Map(ah.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),Mk=10,Dk=20,B_=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),ih=[["init",Cm],["install",Rm],["uninstall",Om],["explore",xm],["manage",Mm],["describe",Pm],["reload",Dm],["doctor",Um],["catalog",Gm],["adopt",jm],["adopt-all",Nm],["activate",Lm],["deactivate",$m],["migrate",Fm]],Uk=[...ih.map(([e,t])=>e==="init"?[e,Im]:[e,t]),["upgrade",cr]],Gk=[...ih.map(([e,t])=>[`extension ${e}`,t]),...Uk.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",bo],["config",Tm],["extension",ko],["package",sr],["packages",sr],["install",qm],["create",Io],["item mutate",sp],["item complete",cp],["item reopen",lp],["copy",Ro],["focus",Oo],["update",xo],["update-many",Po],["upgrade",cr],["calendar",lr],["cal",lr],["context",dr],["ctx",dr],["get",Lo],["search",Uo],["eval",mp],["events",No],["workspace",Ct],["workspace position",[]],["workspace snapshot",Ct],["workspace snapshot create",Ct],["workspace snapshot list",Ct],["workspace snapshot inspect",Ct],["workspace snapshot restore",Ct],["workspace snapshot delete",Ct],["next",Do],["aggregate",go],["deps",Fo],["graph",Mo],["guide",$o],["reindex",Km],["history",yo],["history-compact",km],["history-attest",Sm],["history-redact",vm],["history-repair",bm],["history-author-acknowledge",wo],["merge",wm],["schema",Em],["profile",Am],["plan",vo],["restore",Bm],["delete",Vm],["close",zm],["close-many",So],["append",Eo],["claim",Hm],["release",Wm],["start-task",Ym],["pause-task",Jm],["close-task",Xm],["comments",fm],["notes",_m],["learnings",hm],["files",gm],["docs",ym],["test",ep],["test-runs-worker",[]],["test-all",tp],["telemetry",np],["test-runs",rp],["gc",op],["stats",Ao],["ops",[]],["duplicates",To],["validate",ap],["health",Co],["assurance",ip],...pp,["contracts",Go],["completion",jo],["activity",dp],...[...th].map(e=>[e,ho])],Or=new Map(Gk);for(let{alias:e,canonical:t}of ke){let n=Or.get(e);n!==void 0&&Or.set(t,n)}function jk(e){return oh.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function V_(e){let t=ke.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Ts.includes(e)?ye(e):e.startsWith("extension-")?ye(`extension ${e.slice(10)}`):e.startsWith("package-")?ye(`package ${e.slice(8)}`):e.startsWith("item-")?ye(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ye(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ye(`templates ${e.slice(10)}`):Ka.has(e)?rh.get(e)??ye(e):null}function qk(e,t){let n=B(t);return n!==t||ke.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:gt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function gt(e){return e.split("|").map(t=>ye(t)).filter(t=>t.length>0)}function Kk(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let a of gt(o.command_path)){let i=a.split(" ").filter(s=>s.length>0);if(i.length!==0)for(let s=i.length;s>0;s-=1){let c=i.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,a)=>o.localeCompare(a))}function qa(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function xr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function zk(e,t){if(!t)return{...e};let n=xr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let a=o.action;return typeof a!="object"||a===null?!1:a.const===t});return{...e,oneOf:n}}function kc(e,t){let n=xr(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let a=o.action;if(typeof a!="object"||a===null)return!1;let i=a.const;return typeof i=="string"&&t.has(i)});return{...e,oneOf:n}}function ye(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function sh(e){return e.replace(/\s+/g,"-")}function at(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function W_(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=at(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Sc(e,t,n){n&&(e[t]=!0)}function Y_(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Hk(e){let t=Y_(e.long,"long"),n=Y_(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Sc(o,"required",e.required===!0),Sc(o,"repeatable",e.repeatable===!0),Sc(o,"list",e.list===!0);let a=at(e.description);a&&(o.description=a);let i=at(e.value_name);i&&(o.value_name=i);let s=[at(e.value_type),at(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return s&&(o.value_type=s),o}function ch(e){let t=new Map;for(let r of e){let o=ye(r.target_command);if(o.length===0)continue;let a=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;a.sourceDedupe.has(i)||(a.sourceDedupe.add(i),a.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=Hk(s);if(!c)continue;let m=`${c.flag}|${c.short??""}`;a.dedupe.has(m)||(a.dedupe.add(m),a.flags.push(c))}t.set(o,a)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((a,i)=>{let s=a.layer.localeCompare(i.layer);return s!==0?s:(a.name??"").localeCompare(i.name??"")})});return n}function Bk(e){let t=ch(e.flagRegistrations),n=new Map;for(let a of e.commandDefinitions){let i=ye(a.command);if(i.length===0)continue;let s=at(a.action)??sh(i),c=Array.isArray(a.arguments)?a.arguments.map(m=>{let p=at(m.name);return p?{name:p,required:m.required===!0,variadic:m.variadic===!0,description:at(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{...a.tier===void 0?{}:{tier:a.tier},command:i,action:s,source:{layer:a.layer,name:a.name},description:at(a.description),intent:at(a.intent),arguments:c,flags:t.get(i)?.flags??[],examples:W_(a.examples),failure_hints:W_(a.failure_hints)})}let r=new Set;for(let a of e.handlers)r.add(ye(a));for(let a of n.keys())r.add(a);for(let a of t.keys())r.add(a);let o=[];for(let a of[...r].sort((i,s)=>i.localeCompare(s))){let i=n.get(a);o.push(Vk(a,i,t.get(a)?.flags??[]))}return o}function Vk(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:sh(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Wk(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let n=t.replace(/-([a-z0-9])/g,(r,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return n.length>0?n:null}function Yk(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function Jk(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function Xk(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=Yk(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let a=Wk(o);!a||n[a]!==void 0||(n[a]=Jk(o,e.action),o.required===!0&&r.push(a))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Qk(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function Zk(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((a,i)=>a.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(a=>`${a.flag}|${a.short??""}`));for(let a of n.flags){let i=`${a.flag}|${a.short??""}`;if(!o.has(i))o.add(i),r.flags.push(a);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);s&&Qk(s,a)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function eS(e,t=A){let n={mode:At.extensions.policy.mode,trust_mode:At.extensions.policy.trust_mode,default_sandbox_profile:At.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await j(re(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),a=await ar({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await ir({...a,loaded:a.loaded});return{handlers:new Set(i.commands.handlers.map(s=>ye(s.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:a.policy.mode,trust_mode:a.policy.trust_mode,default_sandbox_profile:a.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function tS(e,t={}){let n=new Map;for(let r of Cs){let o=Ka.has(r);if(o&&!t.includePackageOwnedActions)continue;let a=V_(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:a})}if(t.includePackageOwnedActions)for(let r of Ka)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:V_(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ke.find(o=>o.alias===r.command)?.canonical??ye(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function nS(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!rn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?gt(e.command_path):[],r=n.some(i=>t.handlers.has(i)||t.handlers.has(B(i))),o=n.map(i=>nh.get(B(i))).find(i=>typeof i=="string"),a=t.disabledReason===null&&r;return{action:e.action,invocable:a,available:a,requires_extension:!0,provider:"extension",disabled_reason:a?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function lh(e){return Or.get(e)??_o}function rS(e){return rn.has(B(e))?!1:Or.has(e)}function oS(e){return th.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function J_(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function aS(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function iS(e){let t=new Map;for(let r of e.definitions){let o=J_(r.cli_flag);if(!o)continue;let a=r.cli_aliases.map(s=>aS(s)).find(s=>s!==null),i=r.cli_aliases.map(s=>J_(s)).filter(s=>s!==null&&s!==o);for(let s of r.commands){let c=t.get(s)??{flags:[],seen:new Set},m=a?{flag:o,short:a}:{flag:o},p=`${m.flag}|${m.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(m));for(let u of i){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(s,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Ss(o.flags));return n}function X_(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let a=`${o.flag}|${o.short??""}`;r.has(a)||(r.add(a),n.push(o))}return Ss(n)}function sS(e,t,n,r,o){let a=new Map(t);for(let{alias:i,canonical:s}of ke){let c=t.get(s)??t.get(i);c&&(a.set(i,c),a.set(s,c))}return e.map(i=>{let s=rS(i),c=s?lh(i):[],m=n.get(oS(i))??[],p=a.get(i),u=X_(c,m),f=X_(u,p?.flags??[]),_=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:i,flags:f,...r?{canonical_command:mh(i),visibility:dh(i,o),positionals:pm(i)?.slots??[],flag_invocations:mr(i,f)}:{},provider:_,extension_sources:p?.sources}}).sort((i,s)=>i.command.localeCompare(s.command))}function cS(e,t=Jt){let n=new Set(e),r=new Map;for(let o of ah){let a=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:a,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let a=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};a.aliases.includes(o.alias)||a.aliases.push(o.alias),a.contracts.push(o),r.set(o.canonical,a)}return[...r.values()].map(({contracts:o,...a})=>o.length===0?a:{...a,contracts:o}).sort((o,a)=>o.canonical.localeCompare(a.canonical))}function lS(){return{create_string_options:nu,create_repeatable_options:Zo,update_string_options:ru,update_repeatable_options:ou,list_string_options:sm,search_string_options:cm,calendar_string_options:lm,context_string_options:dm,activity_string_options:mm}}function Q_(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let s of e.required_create_fields)n.add(s);for(let s of e.required_create_repeatables)n.add(s)}let r=Tn(e,"create",n),o=[...new Set(r.required)].sort((s,c)=>s.localeCompare(c)),a=[...new Set(o.map(s=>Ae("create",s)))].sort((s,c)=>s.localeCompare(c)),i=[...new Set(e.options.filter(s=>s.required===!0).map(s=>s.key))].sort((s,c)=>s.localeCompare(c));return{required_option_keys:o,required_flags:a,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function dS(e){let t={},n={};for(let r of[...e.types].sort((o,a)=>o.localeCompare(a))){let o=e.by_type[r];t[r]=Q_(o,"strict"),n[r]=Q_(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function mS(e,t){let n=xr(e);if(n.length===0)return e;let r=!1,o=n.map(a=>{let i=a.properties;if(typeof i!="object"||i===null)return a;let s=i.action;return typeof s!="object"||s===null||s.const!=="create"?a:(r=!0,{...a,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function pS(e){let t=qa(e.action)!==void 0||qa(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,a=e.flagsOnly===!0,i=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,m=qa(e.action),p=qa(e.command),u=!r&&!c&&!o&&!a&&!i&&!m&&!p;return{selectedAction:m,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:a,availabilityOnly:i,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function uS(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function fS(e,t=A){try{return await t(e)}catch{return structuredClone(At)}}async function _S(e,t,n){let r=await fS(t),o=await eS(e),a=x(r,o.registrations??O()),i=nt(r.schema),s=Bk(o);return{settings:r,runtimeProbe:o,typeRegistry:a,statusRegistry:$(r.schema),runtimeFieldRegistry:i,runtimeFieldFlagMap:iS(i),createRequiredOptionContracts:dS(a),extensionContracts:s,mergedExtensionContracts:Zk(s.filter(c=>za(n,c.command,s))),extensionFlagMap:ch(o.flagRegistrations)}}function Z_(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ka.has(e.selectedAction)||e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand)))}function hS(e,t){let n=tS(t,{includePackageOwnedActions:Z_(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Up);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(a=>a.action===o.action)?.tier??ea(o.action))!=="internal"))}return Z_(e)&&e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:jk(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function gS(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function yS(e,t){return[...new Set([...Ts.filter(n=>!rn.has(B(n))),...[...Or.keys()].filter(n=>!rn.has(B(n))),...e.flatMap(n=>n.command_path?gt(n.command_path).filter(r=>n.provider==="extension"||!rn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=ke.find(a=>a.alias===r||a.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>ye(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function wS(e,t){let n=t.slice(0,Mk),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),a=t.slice(0,Dk),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),s=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,d.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:i,nextSteps:[`Retry with a child command, for example: ${i[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:a.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function vS(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function bS(e){return new l(`Unknown command: "${e}".`,d.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function kS(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(n.length>0)throw wS(e.selectedCommand,n);let r=nh.get(B(e.selectedCommand));throw r?vS(e.selectedCommand,r):bS(e.selectedCommand)}function SS(e,t){let n=hS(e,t.mergedExtensionContracts);gS(e,n);let r=yS(n,t.mergedExtensionContracts);kS(e,r);let o=e.selectedCommand?oh.get(B(e.selectedCommand)):void 0,a=e.selectedCommand?n.filter(m=>o?m.action===o:qk(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!a.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let i=e.selectedAction?a.filter(m=>m.action===e.selectedAction):a,s=[...new Map(i.map(m=>nS(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?s.filter(m=>m.invocable):s;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:a,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function ES(e){return new Set(xr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function AS(e){let t=Zp,n=xr(t),r=ES(t),o=e.filter(a=>!r.has(a.action)).map(a=>Xk(a));return o.length>0?{...t,oneOf:[...n,...o]}:t}function eh(e,t,n){let r=new Set(t.actionDescriptors.map(a=>a.action)),o=e.selectedAction?zk(n,e.selectedAction):e.selectedCommand?kc(n,new Set(t.scopedActionDescriptors.map(a=>a.action))):kc(n,r);return e.runtimeOnly&&!e.selectedAction?kc(o,new Set(t.actions)):o}function TS(e,t,n){let r=AS(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?mS(eh(e,n,r),t.createRequiredOptionContracts):eh(e,n,r);return{mergedSchema:r,filteredSchema:o}}function CS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Kk(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function dh(e,t){return t.find(n=>B(n.command)===B(e))?.tier??ea(e)}function za(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||dh(t,n)!=="internal"}function IS(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Jt.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of Ec.keys())r.add(o);return t.filter(o=>!r.has(o)&&za(e,o,n))}function mh(e){let t=ke.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Ec.get(n)??n}var RS=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),OS=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function xS(e,t){let n=B_.get(B(e))??(e.includes(" ")?void 0:B_.get(mh(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>gt(m.command).some(p=>B(p)===B(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),a=o.at(-1),i=o.slice(0,-1).join(" "),s=RS.get(a),c=OS.get(e)??i;return{intent:s===void 0||i.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function PS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ye))].filter(a=>a.length>0).sort((a,i)=>a.localeCompare(i)).map(a=>{let i=Fs(a,{generateFallback:!0}),s=a.split(" ")[0],c=Ec.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),m=new Set([...lh(a).map(f=>f.flag),...t.filter(f=>gt(f.command).some(_=>B(_)===B(a))).flatMap(f=>f.flags.map(_=>_.flag))]),p=(H_.get(B(a))??H_.get(c)??Fk).filter(f=>m.has(f)),u=xS(a,t);return{command:a,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function NS(e){return e.map(t=>({budget:Fs(t,{generateFallback:!0}),envelope:du(t)}))}function LS(e){let t=new Map;for(let n of e){let r=iu(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,a=o.join(","),i=t.get(a)??{commands:[],exit_codes:o};i.commands.push(n),t.set(a,i)}return[...t.values()]}function $S(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>gt(r.command).some(o=>B(o)===B(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>gt(o.command).some(a=>r.has(a)))}return t.extensionContracts.filter(r=>za(e,r.command,t.extensionContracts))}function FS(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function MS(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=mu);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,a])=>[o,[...new Set(a.map(i=>`--${i.cli_flag}`))].sort((i,s)=>i.localeCompare(s))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Op],services:[...xp],policy_modes:[...Pp],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...$p],trust_modes:[...Np],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Lp],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Gd],create_modes:[...jd],close_validation_modes:[...qd],workflow_enforcement_modes:[...Kd]},e.relationship_kind_contracts=[...Vd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,a)=>o.kind.localeCompare(a.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function DS(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function US(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=sS(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let a=new Set(r);e.list_projections=Object.entries(fu).filter(([i])=>a.has(i)).map(([i,s])=>({command:i,default:s,brief_fields:[...uu],compact_fields:[...pu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:a,aliases:i})=>({canonical:a,aliases:i})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function GS(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=lS();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function jS(e,t,n,r){e.command_summaries=PS(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Kp],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(ye))].filter(o=>Ds(o)!==void 0).sort((o,a)=>o.localeCompare(a)).map(o=>({command:o,modes:[...Hp(o).keys()]}))}:{}},e.grammar_contracts={nouns:Xt.nouns,shared_verbs:Xt.shared_verbs,scope_before_verb:Xt.scope_before_verb,visible_top_level_ceiling:Xt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Xt.ceiling_raise_requires_pm_item,positional_shape_budget:Xt.positional_shape_budget,positional_shape_count:new Set(ks.map(({slots:o})=>um(o))).size,positional_action_count:bs.length,positional_action_parents:[...new Set(bs.map(({parent:o})=>o))].sort((o,a)=>o.localeCompare(a)),...r.includePositionalSignatures?{positional_signatures:ks}:{}}}async function Ac(e,t){let n=pS(e);uS(n);let r=E(process.cwd(),t.path),o=await _S(t,r,n),a=SS(n,o),i=TS(n,o,a),s=CS(n,a),c=IS(n,s,o.extensionContracts),m=FS(n,i,a,c),p=$S(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&jS(m,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return m;let f=cS(a.commandCatalog.filter(_=>za(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||MS(m,o,n),DS(m,n,i,p),US(m,n,o,c,f),GS(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...df],gate_triggers:[...lf]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=fo.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=z_(),m.context_intents=Wp(),m.read_output_dimensions=Ms,m.error_codes=su,m.command_output_contracts=NS(c),m.diagnostic_output_contracts=zp,m.command_exit_contracts={vocabulary:au,command_sets:LS(c)}),m}import{readFile as qS}from"node:fs/promises";import KS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();var Tc="context-intents.json";function Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zS(e,t,n){if(!Ha(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="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:r,token_budget:e.token_budget}}function ph(e,t){let n=Array.isArray(e)?e:Ha(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((r,o)=>zS(r,t,o))}async function HS(e){let t=KS.join(e,Tc),n;try{n=await qS(t,"utf8")}catch(o){if(Wt(o))return[];throw await Ju(e),o}let r;try{r=JSON.parse(n)}catch(o){let a=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Tc}: ${a}`,{cause:o})}return ph(r,Tc)}function BS(e){if(!Ha(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Ha(n)?n.contextIntents??n.context_intents:void 0}function VS(e){return e.flatMap(t=>{let n=BS(t.module);return n===void 0?[]:ph(n,`package ${t.name}`)})}async function WS(e){let t=await HS(e.pmRoot),n=VS(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Cc(e,t){let n=await WS(e);return await Yp(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();async function uh(e,t,n=Vp){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(a=>typeof a=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as YS}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93e1b043-89b2-546e-b238-1b9f4a1df742")}catch{}})();function Ic(e){let t=Wd();for(let n of e)t.register(n);return t}function JS(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(Ys(t));for(let a of n){let i=a.split("."),s=o;for(let p of i){let u=gs(s);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(p)||["constructor","prototype","__proto__"].includes(p)||u===null||!Object.hasOwn(u,p))throw new l(`Invalid owned settings subtree: ${a}. Select a declared inline object path.`,d.USAGE);s=u[p]}if(gs(s)===null)throw new l(`Invalid owned settings subtree: ${a}. Select a declared inline object path.`,d.USAGE);let c=r,m=o;for(let p of i.slice(0,-1)){let u=c[p];m=m[p],u===void 0&&Object.defineProperty(c,p,{value:structuredClone(m),enumerable:!0,writable:!0,configurable:!0}),c=c[p]}Object.defineProperty(c,i.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return Le(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
+ `}function fh(e,t,n,r){return{client:t,isItemNotFoundError:o=>Ta(o)&&o.exitCode===d.NOT_FOUND,getItemAt:(o,a)=>uf(o,a,{pmRoot:e}),openRelationshipEventStore:o=>_f.open({pmRoot:e,nodes:o.nodes,registry:Ic(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Jd(o.nodes,o.edges,Ic(o.definitions)),analyzeRelationshipImpact:(o,a,i)=>hf(o,a,i),validateRelationshipEvents:o=>{let a=new ff(o.nodes,{registry:Ic(o.definitions)});return o.events.map(i=>a.append({...i,expectedVersion:a.version}))},commitWorkspaceTransaction:o=>gf({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new l("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",d.USAGE);let a=o.dryRun===!0?await Mu(e,()=>A(e)):await A(e);try{let i=await aa({pmRoot:e,filePath:re(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${YS("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:n??C(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async s=>{let c=s===null?null:JSON.parse(s),m=ta(c);if(!m.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",d.USAGE);let p=Ws(m.data),u=await o.mutate(structuredClone(p));if(!ta(u).success)throw new l("Workspace settings mutation returned invalid settings.json.",d.USAGE);let f=Le(p,u)?s:Ys(u,{source:{raw:c,validated:m.data}});f=JS(f,u,o.replaceSubtrees);let _=ta(JSON.parse(f));if(!_.success)throw new l("Workspace settings mutation serialized invalid settings.json.",d.USAGE);return{raw:f,result:o.includePreview===!0?Ws(_.data):void 0}}});return i.changed&&o.dryRun!==!0&&await Y({path:re(e),scope:"project",op:"extension:pm:settings"}),{changed:i.changed,dry_run:o.dryRun===!0,replayed:i.replayed===!0,...i.result===void 0?{}:{preview:i.result}}}finally{Fu(e)}}}}import XS from"node:fs/promises";import Q from"node:path";import QS from"node:readline/promises";import{stdin as ZS,stdout as De}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="95053097-fc76-5587-ab41-8cb05b9d3cd9")}catch{}})();var Oc=Symbol.for("pm.sdk.init-invocation-cwd");var eE=()=>QS.createInterface({input:ZS,output:De});function tE(){return structuredClone(At)}var nE=["minimal","default","strict"];function hh(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${nE.join(", ")}`,d.USAGE)}function rE(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return gp(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${hp.join(", ")}`,d.USAGE)}}}function oE(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function Rc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:Q.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function aE(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||Rc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=Q.resolve(e,o),p=Q.join(m,".agents","pm");return{pmRoot:p,prefixArg:n,target:{mode:"workspace-path",tracker_root:p,workspace_root:m}}}if(t.path===void 0&&Rc(n)){let m=Q.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let a=E(e,t.path),i=Q.join(Q.resolve(e),".agents","pm"),s=Q.dirname(Q.dirname(a)),c=Q.resolve(a)===i?"current":"ancestor";return{pmRoot:a,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:a,workspace_root:s,discovery:c,requested_cwd:Q.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:a}}}function iE(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(Rc(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Lt(e)!==Lt(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Lt(e)}`,`pm init --id-prefix ${Lt(t)}`]});return t}function sE(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${Uf.join(", ")}`,d.USAGE)}function cE(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function gh(e,t){let n=Bd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function lE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dE(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(lE).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function mE(e,t,n){let r=zo(t.schema),o=pt(e,r.files.types,mt.types),a=fp(await X(o)),i=[],s=[];for(let c of yp(n)){let m=_p(a,c);a=m.file,(m.replaced?s:i).push(m.definition.name)}return await Ve({pmRoot:e,filePath:o,raw:qo(a),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:i,updated:s,file:o}}async function pE(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",Q.join(".agents","pm")];for(let n of t)if(await j(Q.join(e,n)))return!0;return!1}async function uE(e,t,n){if(!t||n||await j(Q.join(e,"settings.json"))||!await pE(e))return;let r=Q.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function yh(e,t){let n=[],r=[];for(let o of t){let a=o?Q.join(e,o):e,i=await j(a);await XS.mkdir(a,{recursive:!0}),i?r.push(`already_exists:${a}`):n.push(a),r.push(...await Y({path:a,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function fE(e,t){let n=eE();try{De.write(`pm init setup wizard (agent-optimized)
3
+ `),De.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
3
4
 
4
- `),Me.write(`1/3 Item ID prefix
5
- `),Me.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
6
- `);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?Lt(r):e;Me.write(`
5
+ `),De.write(`1/3 Item ID prefix
6
+ `),De.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
7
+ `);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?Lt(r):e;De.write(`
7
8
  2/3 Governance preset
8
- `),Me.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
9
- `),Me.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
10
- `),Me.write(`strict: ownership blocking, strict create defaults, close validation strict.
11
- `);let a=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=a.trim().length>0?a.trim():"minimal",s="minimal";try{s=_h(i)}catch{Me.write(`Unrecognized governance preset "${i}"; using minimal.
12
- `)}Me.write(`
9
+ `),De.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
10
+ `),De.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
11
+ `),De.write(`strict: ownership blocking, strict create defaults, close validation strict.
12
+ `);let a=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=a.trim().length>0?a.trim():"minimal",s="minimal";try{s=hh(i)}catch{De.write(`Unrecognized governance preset "${i}"; using minimal.
13
+ `)}De.write(`
13
14
  3/3 Project telemetry
14
- `),Me.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
15
- `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),p=sE(m,t);return Me.write(`
16
- `),{prefix:o,preset:s,telemetry_enabled:p}}finally{n.close()}}function fE(e){return{presetFromOption:_h(e.preset),useDefaults:e.defaults===!0,authorFromOption:rE(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:iE(e.agentGuidance),typePreset:nE(e.typePreset)}}function _E(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function hE(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function gE(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(hh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function yE(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=_E({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return hE(e.settingsPath,n,e.options.force===!0,e.target),gE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await $e(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function wE(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await uE(t,At.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let a=n??"minimal",i=eE();i.id_prefix=t,hh(i,a);let s=ra()?.trim()||void 0;return i.author_default=e.normalizedOptions.authorFromOption??s??"",r!==void 0&&(i.telemetry.enabled=r,i.telemetry.first_run_prompt_completed=!0),await $e(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function fh(e){return e.settingsExists?await yE(e):await wE({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function vE(e){let t=await Df({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await $e(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function bE(e,t){let n=[],r=[],o=await vp(e,t.schema);for(let a of o.created_paths)n.push(a),r.push(...await Y({path:a,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function kE(e){if(e.typePreset===void 0)return;let t=await dE(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await Y({path:t.file,scope:"project",op:"init:type_preset"})),t}async function SE(e){let t=x(e.settings,O()).folders.filter(r=>!hs.includes(r)),n=await gh(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function EE(e){let t=X.resolve(e.tracker_root),n=X.dirname(t);return X.basename(t)==="pm"&&X.basename(n)===".agents"?X.dirname(n):e.workspace_root}async function AE(e,t,n,r){if(!e)return;let o=await Gn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let a=lE(o),i=a.packages.filter(s=>!s.ok).map(s=>s.alias);if(!a.installed_all||i.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,d.GENERIC_FAILURE);return a}function TE(e){let t=r=>Zt([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function CE(e,t,n,r=yf){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function IE(e,t,n,r){if(e==null||n==="status")return;let o=await ec(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Nr(e,t,n={}){let r=t[Rc],o=typeof r=="string"?r:process.cwd(),a=oE(o,t,e,n.workspace),i=a.pmRoot;e=aE(a.prefixArg,n.idPrefix);let s=fE(n);await pE(i,a.target.mode==="tracker-path",n.force===!0);let c=[],m=[],p=X.join(i,"settings.json"),u=await j(p),f;u&&(f=await fh({pmRoot:i,settingsPath:p,settingsExists:u,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:a.target}));let _=await gh(i,hs);c.push(..._.createdDirs),m.push(..._.warnings),f??=await fh({pmRoot:i,settingsPath:p,settingsExists:u,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:a.target});let{settings:h}=f,y=EE(a.target),g=await Ta(y??X.dirname(i)),w=y??g,b=await vE({pmRoot:i,cwd:w??o,agentGuidanceMode:s.agentGuidanceMode,settings:h,warnings:m}),S=await bE(i,h);c.push(...S.createdDirs),m.push(...S.warnings);let T=await kE({pmRoot:i,settings:h,typePreset:s.typePreset,warnings:m});T&&(h=await A(i)),await SE({pmRoot:i,settings:h,createdDirs:c,warnings:m}),await IE(w,i,s.agentGuidanceMode,m),!u&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await CE(i,g,m);let L=await AE(s.installBundledPackages,t,i,m),P=TE({installBundledPackages:s.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:a.target});return{ok:!0,path:i,target:a.target,settings:h,created_dirs:c,warnings:m,governance_preset:h.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...L?{installed_packages:L}:{},next_steps:P,agent_guidance:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ad3dd1-a1ec-5ee8-9f0f-1350dd91f25e")}catch{}})();async function yh(e,t){let n=E(t??process.cwd(),e),r=await A(n);return fe(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="247354d6-fccb-58f8-b969-b1952abf181e")}catch{}})();var RE={"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 wh(e){return Object.fromEntries(Fp.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var vh={ctx:{action:"context"},...RE,...wh("extension"),...wh("package"),...Object.fromEntries(Mp.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="baa27a48-c538-574c-9d05-1f1c0f4f429c")}catch{}})();function bh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function OE(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 Oc(e,t){let n=OE(t),r=n==="brief"?n:bh(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:bh(e.filters)?e.filters:{},projection:r}}}import{readFile as xE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();function Va(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ie(e,t)}function kh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function xc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function on(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Hn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=de(n,"--add");return Object.keys(o).map(a=>a.trim().toLowerCase()).some(a=>a!=="text")?n:o.text?.trim()||n}catch{return n}}function Pc(e){return typeof e=="object"&&e!==null&&"code"in e}function $r(e,t){if(!ft(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function PE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let n=Nt(),r=ft(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return $r(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let o=e.file.trim();if(!o)throw new l("--file path cannot be empty",d.USAGE);if(o==="-")return $r(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await xE(o,"utf8"),emptyFlag:"--file"}}catch(a){if(Pc(a)&&Wt(a))throw new l(`--file path not found: ${o}. Use --file - to read stdin.`,d.USAGE);let i=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${o}": ${i}. Use --file - to read stdin.`,d.USAGE)}}async function Wa(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await PE(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Lr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Eh(e){return e==="comments"?"--stdin":"--add -"}function NE(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let n=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(n))return;let r=Eh(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${n}" looks like an option, not annotation text. Use ${r} to read stdin, or use text=${n} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${r} for stdin input, pass plain text, or use text=${n} when the text really starts with "-".`,examples:[`${o} ${r}`,`${o} --add text=${n}`]})}function LE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Eh(e.collectionKey)}`]})}function $E(e,t,n,r,o,a){let i=on(e.metadata,t),s=o?i.findIndex(c=>c.author===n&&c.text===r):-1;return s>=0?{changedFields:[],entryIndex:s+1}:(i.push(a({created_at:k(),author:n,text:r})),e.metadata[t]=i,{changedFields:[t],entryIndex:i.length})}async function Bn(e,t,n,r){LE(r,t);let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=x(a,O()),s=yr(t.limit);if(r.input.mode==="list"){let h=await q(o,e,a.id_prefix,a.item_format,i.type_to_folder);if(!h)throw new l(`Item ${e} not found`,d.NOT_FOUND);let y=await se(h,{schema:a.schema}),g=on(y.document.metadata,r.collectionKey);return Ba(h.id,r.collectionKey,g,s,t.includeMeta===!0)}let c=C(t.author,a.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,y;try{y=await ce({pmRoot:o,settings:a,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=on(w.metadata,r.collectionKey),S=Sh(r.input.index,b.length,r.collectionKey);return kh(b[S],"deleted"),b.splice(S,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Lr(w,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return Ba(y.item.id,r.collectionKey,g,s,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";NE(m,r);let p=r.parseText(r.input.value??"");if(!p.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let h=r.editOp??r.op,y;try{y=await ce({pmRoot:o,settings:a,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=on(w.metadata,r.collectionKey),S=Sh(r.input.index,b.length,r.collectionKey),T=b[S];return kh(T,"edited"),b[S]={...T,text:p,edited_at:k()},w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Lr(w,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return Ba(y.item.id,r.collectionKey,g,s,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:g[r.input.index-1]},t.fullHistory===!0)}let u,f=0;try{u=await ce({pmRoot:o,settings:a,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let y=$E(h,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(h){Lr(h,r.conflictGuidance)}let _=on(u.item,r.collectionKey);return Ba(u.item.id,r.collectionKey,_,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Sh(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,a=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${a})`,d.USAGE)}return e-1}function FE(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Ba(e,t,n,r,o,a,i=!1){let s=a===void 0||i?xc(n,a!==void 0&&i?void 0:r):a.entry===void 0?[]:[a.entry],c=a!==void 0&&s.length<n.length;return{id:e,[t]:s,count:s.length,...a?.changedCount===void 0?{}:{changed:a.changedCount===1},...[o,a!==void 0].includes(!0)?{total_count:n.length,returned_count:s.length,has_more:c||s.length<n.length,...r!==void 0?{limit:r}:{}}:{},...FE(t,a,c)}}import{readFile as ME}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8513dce5-85a0-56aa-bb8f-c64756ac4b2e")}catch{}})();async function Nc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",a=Number(n)+Number(r)+Number(o);if(a===0)return;if(a>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",ft(e))??"",emptyFlag:"--add"};if(r)return $r(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return $r(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await ME(i,"utf8"),emptyFlag:"--file"}}catch(s){if(Pc(s)&&Wt(s))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let c=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${i}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function DE(e,t){let n=e.edit,r=e.delete,o=n!==void 0,a=r!==void 0;if(o&&a)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(a){if(await Nc(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let s=await Nc(e,t);if(s===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:s.value,emptyFlag:s.emptyFlag}}let i=await Nc(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function Ah(e,t,n){let r=Nt(),o=await DE(t,r),a=o.mode==="add"||o.mode==="edit",i=o.value??"";return Bn(e,t,n,{input:{...o,rawValue:t.add??i,value:a?Hn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:s=>s,createEntry:s=>s,bypassOwnershipConflict:!!(o.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(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78e92b9c-f3da-594e-8158-00409222308f")}catch{}})();var Th=new Set(["item_format"]),Ch=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),UE=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),GE=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),jE={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function qE(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Th.has(t)||Ch.has(t)||UE.has(t)||t==="context")return t}function KE(e){let t=e.trim().toLowerCase();return jE[t]??e}function Ih(e,t){let n=qE(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:Th.has(n)?{routable:!0,flag:"format",value:t}:Ch.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:GE.has(n)?KE(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="544840da-22f5-5734-81ec-e12c5612545c")}catch{}})();var zE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Rh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>128)throw new Error("A legacy author must contain 1-128 characters.");return t}function HE(e){let t=e?.trim().toLowerCase();if(!t||!zE.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function BE(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function VE(e,t){let n=new Set;for(let r of(e??[]).slice(0,1e4)){let o=r.trim().slice(0,128);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function WE(e,t){let n=Rh(t.legacy_author),r=HE(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function YE(e,t){if(t.operation==="add")return WE(e,t);if(t.operation==="remove"){let r=Rh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Lc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Oh(e,t){let n=e?.version??1,r={...e?.aliases},o=YE(r,t),a={version:o?n+1:n,aliases:BE(r)};return{vocabulary:a,preview:{operation:t.operation,changed:o,version_before:n,version_after:a.version,alias_count:Object.keys(a.aliases).length,residual_author_count:VE(t.observed_authors,a.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d9b6f2ba-2c5e-52ea-891d-53124601fb89")}catch{}})();var xh=["project","global"],yt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},JE=Object.keys(yt).map(e=>yt[e][0]),XE=Object.fromEntries(Object.keys(yt).flatMap(e=>yt[e].map(t=>[t,e]))),QE={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},ZE=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],eA=new Set(["metadata_required_fields",...ZE]),tA=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),nA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),rA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),oA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),aA=new Set(["governance_preset","governance_create_default_type"]),Fh=e=>eA.has(e),iA=e=>rA.has(e),sA=e=>oA.has(e),cA=e=>aA.has(e);function $c(e){return e==="definition_of_done"||Fh(e)}function lA(e){if(xh.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${xh.join(", ")}`,d.USAGE)}function dA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Ce({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function mA(e){let t=XE[e];if(t)return t;let n=Ss.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${JE.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function pA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function uA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function Mh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function fA(e){return Mc(e,"test-result-tracking")}function Mc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Dh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Dc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function Uh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function Gh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function jh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function qh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function Kh(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function zh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function Hh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}var _A={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Ph(e,t){let n=_A[e];if(n)return Mc(t,n);switch(e){case"history_missing_stream_policy":return Mh(t);case"sprint_release_format_policy":return Js(t);case"parent_reference_policy":case"governance_parent_reference_policy":return ga(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Dc(t);case"governance_preset":return Uh(t);case"governance_ownership_enforcement":return Gh(t);case"governance_create_mode_default":return jh(t);case"governance_close_validation_default":return qh(t);case"governance_require_close_reason":return Hh(t);case"governance_workflow_enforcement":return Kh(t);case"governance_force_required_for_stale_lock":return zh(t);case"telemetry_tracking":return Dh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Nh={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},hA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function gA(e,t){let n=[...new Set((e??[]).map(a=>a.trim()).filter(a=>a.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(a=>a.toLowerCase().replaceAll("-","_")),o=r.filter(a=>Nh[a]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${hA.join(", ")}`,d.USAGE);return[...new Set(r.map(a=>Nh[a]))].sort((a,i)=>a.localeCompare(i))}function yA(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,a)=>o.localeCompare(a));if(n){if(r.length>0)throw new l(`Config set ${yt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${yt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function wA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function vA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return mA(t)}function Bh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var bA={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Lc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Uc(e,t){return bA[t](e)}function Re(e,t){return t.length===0?e:{...e,warnings:t}}async function kA(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):lt(n),o=re(r);return e==="project"&&await I(r),{pmRoot:r,settingsPath:o}}function SA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function Lh(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function EA(e,t,n,r,o){let a=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!_s.includes(c))throw new l(`Context --default-depth must be one of ${_s.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,a=!0)}if(t.activityLimit!==void 0){let c=Lh(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,a=!0)}if(t.staleThresholdDays!==void 0){let c=Lh(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,a=!0)}let s=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of s){let p=SA(m);if(p!==void 0){let u=c;i.sections[u]!==p&&(i.sections[u]=p,a=!0)}}return a&&await $e(n.pmRoot,e,"config:set:context"),Re({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:a},o)}function AA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function TA(e,t,n,r,o,a){if(o===void 0)return a;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return AA(t,o,a);Bh(n);let i=Ih(n,o);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(a.criterion!==void 0&&a.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...a,criterion:i.values}}if(i.flag==="format")return{...a,format:i.value};if(a.policy!==void 0&&Ph(n,a.policy)!==Ph(n,i.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${a.policy}". Pass only one.`,d.USAGE);return{...a,policy:i.value}}function CA(e){let t=Object.keys(yt).map(r=>({key:r,aliases:yt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":$c(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:$c(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:QE[r],value:Uc(e.settings,r)})),n=Ss.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Es(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Re({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function IA(e){let t=Object.fromEntries(Object.keys(yt).map(n=>[n,Uc(e.settings,n)]));return Re({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function RA(e,t){let n=Uc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Re({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Re({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Re({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Re({...r,criteria:n},e.warnings):Re({...r,policy:n},e.warnings)}async function OA(e,t,n,r){if(t==="get"){let s=Es(e.settings,n);return Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let a=Ap(n,o);if(!a.ok)throw new l(a.error.message,d.USAGE);let i=Vo(e.settings,n,a.parsed.value);return i&&await $e(e.target.pmRoot,e.settings,`config:set:${n.path}`),Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function Q(e,t,n){t&&await $e(e.target.pmRoot,e.settings,n)}function $h(e,t,n){return e!==n||t!==n}function me(e,t,n,r){return Re({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Fc(e,t,n,r){return Re({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function xA(e,t){let n=uA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let a=x(e.settings,O()),i=await nf(e.target.pmRoot,n,"config:set:item_format:migrate",a.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await $e(e.target.pmRoot,e.settings,"config:set:item_format")}return Re({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function PA(e,t,n){if(t==="history_missing_stream_policy"){let a=Mh(n.policy),i=e.settings.history.missing_stream!==a;return e.settings.history.missing_stream=a,await Q(e,i,"config:set:history_missing_stream_policy"),me(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let a=Js(n.policy),i=e.settings.validation.sprint_release_format!==a;return e.settings.validation.sprint_release_format=a,await Q(e,i,"config:set:sprint_release_format_policy"),me(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let a=ga(n.policy),i=e.settings.validation.parent_reference!==a||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==a;return e.settings.validation.parent_reference=a,e.settings.governance.preset="custom",e.settings.governance.parent_reference=a,await Q(e,i,"config:set:parent_reference_policy"),me(e,t,e.settings.validation.parent_reference,i)}let r=Dc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Q(e,o,"config:set:metadata_validation_profile"),me(e,t,e.settings.validation.metadata_profile,o)}async function NA(e,t,n){if(t==="metadata_required_fields"){let i=gA(n.criterion,n.clearCriteria),s=i.length!==e.settings.validation.metadata_required_fields.length||i.some((c,m)=>c!==e.settings.validation.metadata_required_fields[m]);return e.settings.validation.metadata_required_fields=i,await Q(e,s,"config:set:metadata_required_fields"),Fc(e,t,[...e.settings.validation.metadata_required_fields],s)}let r={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=yA(t,n.criterion,n.clearCriteria),a=o.length!==r.length||o.some((i,s)=>i!==r[s]);return r.splice(0,r.length,...o),await Q(e,a,`config:set:${t}`),Fc(e,t,[...r],a)}async function LA(e,t,n){if(t==="governance_preset"){let c=Uh(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Q(e,m,"config:set:governance_preset"),me(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Q(e,c,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let a=x(e.settings,O()),i=be(o,a);if(!i)throw new l(Rt(o,a.types,Ot(e.target.pmRoot,e.settings.schema)),d.USAGE);let s=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await Q(e,s,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type,s)}async function $A(e,t,n){if(t==="governance_ownership_enforcement"){let a=Gh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==a;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=a,await Q(e,i,"config:set:governance_ownership_enforcement"),me(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let a=jh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==a;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=a,await Q(e,i,"config:set:governance_create_mode_default"),me(e,t,e.settings.governance.create_mode_default,i)}let r=qh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Q(e,o,"config:set:governance_close_validation_default"),me(e,t,e.settings.governance.close_validation_default,o)}async function FA(e,t,n){if(t==="governance_parent_reference_policy"){let a=ga(n.policy),i=e.settings.governance.preset!=="custom"||$h(e.settings.governance.parent_reference,e.settings.validation.parent_reference,a);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=a,e.settings.validation.parent_reference=a,await Q(e,i,"config:set:governance_parent_reference_policy"),me(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let a=Dc(n.policy),i=e.settings.governance.preset!=="custom"||$h(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,a);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=a,e.settings.validation.metadata_profile=a,await Q(e,i,"config:set:governance_metadata_validation_profile"),me(e,t,e.settings.governance.metadata_profile,i)}let r=Kh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Q(e,o,"config:set:governance_workflow_enforcement"),me(e,t,e.settings.governance.workflow_enforcement,o)}async function MA(e,t,n){if(t==="governance_require_close_reason"){let a=Hh(n.policy)==="enabled",i=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Q(e,i,"config:set:governance_require_close_reason"),me(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",i)}let r=zh(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==r;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=r,await Q(e,o,"config:set:governance_force_required_for_stale_lock"),me(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function DA(e,t,n){if(t==="test_result_tracking"){let a=fA(n.policy)==="enabled",i=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Q(e,i,"config:set:test_result_tracking"),me(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",i)}if(t==="untrusted_linked_test_execution"){let a=Mc(n.policy,"untrusted-linked-test-execution")==="enabled",i=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Q(e,i,"config:set:untrusted_linked_test_execution"),me(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",i)}let r=Dh(n.policy)==="enabled",o=e.settings.telemetry.enabled!==r||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=r,e.settings.telemetry.first_run_prompt_completed=!0,await Q(e,o,"config:set:telemetry_tracking"),me(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function UA(e,t,n){let r=pA(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((a,i)=>a!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await Q(e,o,"config:set:definition_of_done"),Fc(e,t,[...e.settings.workflow.definition_of_done],o)}function GA(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function jA(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function qA(e,t){let{operation:n,dryRun:r}=GA(t.policy),o=jA(n,t.value),a;try{a=Oh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new l(i.message,d.USAGE)}return a.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:a.vocabulary},await Q(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${a.preview.version_after}`)),Re({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Lc(r?e.settings.agent_identity?.identity_vocabulary:a.vocabulary),vocabulary_mutation:a.preview,settings_path:e.target.settingsPath,changed:a.preview.changed&&!r},e.warnings)}async function KA(e,t,n){if(n.clearCriteria===!0&&!$c(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?xA(e,n):t==="context"?EA(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?qA(e,n):t==="definition_of_done"?UA(e,t,n):Fh(t)?NA(e,t,n):tA.has(t)?DA(e,t,n):nA.has(t)?MA(e,t,n):iA(t)?$A(e,t,n):sA(t)?FA(e,t,n):cA(t)?LA(e,t,n):PA(e,t,n)}async function Vh(e,t,n,r,o,a){let i=lA(e),s=dA(t),c=s==="get"||s==="set"?Bo(n):void 0,m=c?void 0:vA(s,n),p=TA(s,n,m,c,a,r),u=await kA(i,o),{settings:f,metadata:_,warnings:h}=await Uu(u.pmRoot),y={scope:i,target:u,settings:f,metadata:_,warnings:wA(h)};return c?OA(y,s,c,p):s==="list"?CA(y):s==="export"?IA(y):(Bh(m),s==="get"?RA(y,m):KA(y,m,p))}import Yh from"node:fs/promises";import Jh from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function zA(e,t,n){let r=new Set,o=[];for(let a of e){let i=a.trim();if(i.length===0||r.has(i))continue;r.add(i);let s=t.get(i);if(s===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(s.entries<=n){o.push({id:i,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:s.entries,selected:!0,skip_reason:null})}return o}function HA(e,t){let n=[...e].sort((o,a)=>a.entries-o.entries||o.id.localeCompare(a.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Wh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return zA(t.ids,n,t.minEntries)}return HA(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6009e5f-840e-5e3a-b8b9-6e9d42d63410")}catch{}})();function BA(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let a=Number.parseInt(n,10),i=Mn(t);if(!Number.isSafeInteger(a)||a<i+1||a>i+t.length+1)throw new l(`history-compact --before version must be between ${i+1} and ${i+t.length+1}.`,d.USAGE);let s=a-i-1;return{kind:"version",raw:n,compactCount:s,retainedCount:t.length-s}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let o=0;for(let[a,i]of t.entries()){let s=Date.parse(i.ts);if(!Number.isFinite(s))throw new l(`History for this item contains invalid timestamp at entry ${a+1}.`,d.GENERIC_FAILURE);if(s>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function VA(e,t){let n=fr(),r=fr();for(let o=0;o<e.length;o+=1){let a=e[o];n=Dn(n,a.patch,o+1,a.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function WA(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Cu.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Hs(hr(e.document),r,ut(n.hash_algorithm)).includes(n.after_hash))}}function YA(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function JA(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function XA(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=VA(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Mn(e.historyEntries,!0),a=e.historyEntries[e.boundary.compactCount-1],i=Le({hashAlgorithm:ut(a.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:rt(fr()),after:rt(t),message:JA(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:Iu(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),s=[Ru({...i,before_hash:Hs(fr(),a.item_hash_version??1,ut(a.hash_algorithm))[0],after_hash:a.after_hash,item_hash_version:a.item_hash_version}),...r];return e.dryRun||s.push(Le({nowIso:k(),author:e.author,op:"history_compact",before:rt(n),after:rt(n),message:YA(e.options,e.boundary)})),{rewrittenEntries:s,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Gc(e,t,n){let{pmRoot:r,settings:o,typeRegistry:a}=await Sr(n.path),i=await tn(r,e,o,a.type_to_folder);return La({pmRoot:r,subject:i,settings:o,typeRegistry:a,operation:"history-compact",options:t,transform:s=>QA(i,t,s)})}function QA(e,t,n){let r=e.historyPath,o=n.entries,a=n.verification;if(!a.ok)throw new l(`history-compact requires a valid history chain (${a.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);let i=BA(t.before,o),s=i.compactCount>0,c=!!t.dryRun,m=n.author,p=[];s||p.push("history_compact_noop_before_boundary");let u=WA(n.loadedItem,o);u.matchedChainBefore===!1&&p.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:h}=XA({historyEntries:o,boundary:i,changed:s,dryRun:c,author:m,options:t}),y=Mn(o,!0),g=i.retainedCount>0&&y!==null?y+i.compactCount+1:null;return{changed:s,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:c,changed:s,compact_boundary:{kind:i.kind,before:i.raw,entries_compacted:i.compactCount,entries_retained:i.retainedCount,first_retained_entry:g},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:h,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...p,...b])].sort((S,T)=>S.localeCompare(T)),generated_at:k()})}}var ZA=3;function eT(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,d.USAGE)}let t=ha(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:_a(t)}}function Xh(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)==0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function tT(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function nT(e){let t=$(e.settings.schema),n=Sa(t),r=await fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),a=Jh.join(e.pmRoot,"history"),i=[],s=[];if(!await j(a))return{candidates:i,preselectionErrors:s};let c=(await Yh.readdir(a)).filter(m=>m.endsWith(".jsonl")).sort((m,p)=>m.localeCompare(p));for(let m of c){let p=Jh.join(a,m),u=m.slice(0,-6);try{let f=await Yh.readFile(p,"utf8");await Rn({path:p,scope:"project"}),i.push({id:u,entries:tT(f),bucket:o.get(u)??null})}catch(f){s.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:s}}async function rT(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Gc(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function Qh(e,t){let n=eT(e),{pmRoot:r,settings:o,typeRegistry:a}=await Sr(t.path),{candidates:i,preselectionErrors:s}=await nT({pmRoot:r,settings:o,typeToFolder:a.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??ZA,p=o.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&p.enabled,f=e.allOver??(u?p.max_entries:void 0),_=Wh(i,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),h=!!e.dryRun,y=[...s],g={streams_considered:i.length+s.length,selected:0,items_compacted:0,items_skipped:0,items_errored:s.length};for(let w of _){let b=await rT({row:w,options:n,dryRun:h,global:t});if(y.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:h,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:u},totals:g,results:y,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="feb8c44f-a6bd-5a7e-9600-eb5c45c0a5b4")}catch{}})();function Zh(e){let t=e.options.all===!0,n=e.id??v(e.options,"id");return f_(n,t),t?$a(e.options,e.global):Ut(n,e.options,e.global)}function eg(e){let t=e.options.ids,n=ha(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.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 r=n===void 0?void 0:_a(n),o=Fe(e.options.allOver??e.options.all_over,"history-compact allOver"),a=Fe(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),i=v(e.options,"scope"),s=[];e.options.closed===!0&&s.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&s.push("all-streams"),(i==="closed"||i==="all-streams")&&s.push(i);let c=[...new Set(s)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return Xh(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?Gc(e.id,{before:v(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global):Qh({ids:r,scope:m,allOver:o,minEntries:a,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global)}import jc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebf3254f-1fed-5972-b91a-b8ff101675f4")}catch{}})();function tg(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function oT(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function aT(e){let t=e.trim();if(t.length===0)throw new l("history-redact --regex requires a non-empty pattern.",d.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=oT(t.slice(o+1)))}if(n.length===0)throw new l("history-redact --regex cannot use an empty pattern.",d.USAGE);try{new RegExp(n,r)}catch{throw new l("Invalid --regex value; provide a valid JavaScript regular expression.",d.USAGE)}return{kind:"regex",source:n,flags:r}}function iT(e,t){let n=[...new Set(tg(e).map(a=>a.trim()))].filter(a=>a.length>0).map(a=>({kind:"literal",value:a})),r=[...new Set(tg(t).map(a=>a.trim()))].filter(a=>a.length>0).map(aT),o=[...n,...r];if(o.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",d.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function sT(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let a=e.indexOf(t,r);if(a===-1)break;o+=1,r=a+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function cT(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function rg(e,t,n){let r=e,o=0;for(let a of t){let i=a.kind==="literal"?sT(r,a.value,n):cT(r,a,n);r=i.value,o+=i.replacements}return{value:r,replacements:o}}function Ya(e,t,n){if(typeof e=="string")return rg(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(o=>{let a=Ya(o,t,n);return r+=a.replacements,a.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[a,i]of Object.entries(e)){let s=Ya(i,t,n);r+=s.replacements,o[a]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function ng(e,t,n){let r=0;return{patch:e.map(o=>{if(!Object.prototype.hasOwnProperty.call(o,"value"))return o;let a=Ya(o.value,t,n);return r+=a.replacements,a.replacements>0?{...o,value:a.value}:o}),replacements:r}}function lT(e){let t=structuredClone(zs),n=0,r=0;for(let o=0;o<e.length;o+=1){let a=e[o];_r(t,void 0,ut(a.hash_algorithm))!==a.before_hash&&(n+=1),t=Dn(t,a.patch,o+1,a.op),_r(t,void 0,ut(a.hash_algorithm))!==a.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function dT(e,t,n){let r=0,o=!1,a=!1,i=e.message;if(typeof e.message=="string"){let m=rg(e.message,t,n);i=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let s=ng(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;let c=e.reanchor_evidence?.map(m=>{let p=m.patch?ng(m.patch,t,n):{patch:void 0,replacements:0},u=m.record?Ya(m.record,t,n):{value:void 0,replacements:0};r+=p.replacements,r+=u.replacements;let f=p.replacements>0||u.replacements>0;if(o||=f,!f)return m;a=!0;let{patch:_,record:h,record_hash:y,record_hash_version:g,...w}=m;return p.replacements>0?w:{...w,patch:m.patch}});return{entry:{...e,message:i,patch:s.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:a}}function mT(e,t,n){let r=structuredClone(zs),o=0,a=0,i=[];for(let s=0;s<e.length;s+=1){let c=e[s],m=Ou(c);if(!m.ok)throw new l(`history-redact refuses invalid immutable record ${s+1} (${m.error}).`,d.GENERIC_FAILURE);let p=dT(c,t,n);a+=p.replacements,p.changed&&(o+=1);let u=_r(r,void 0,ut(c.hash_algorithm));r=Dn(r,p.entry.patch,s+1,p.entry.op);let f=_r(r,void 0,ut(c.hash_algorithm));i.push(xu(c,{...p.entry,before_hash:u,after_hash:f},{retainPriorRecord:p.changed,retainPriorRecordHash:!p.changed}))}return{entries:i,finalDocument:r,entriesChanged:o,replacements:a}}function pT(e){return Object.keys(e.metadata).length>0}function uT(e){if(!pT(e.finalDocument))return{raw:null,path:null,document:null};let t=nt(rt(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",d.USAGE);return{document:t,path:dt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Be(t,{format:"toon",schema:e.settings.schema})}}function fT(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function _T(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??rt(e.rewritten.finalDocument);return t.push(Le({nowIso:k(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function hT(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await $t(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let a=new Map;e.currentItem.path&&e.currentItem.raw!==null&&a.set(e.currentItem.path,e.currentItem.raw);let i=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await ne(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await jc.rm(e.currentItem.path,{force:!0}),await ne(e.subject.historyPath,Nu(e.rewrittenEntries))}catch(c){try{await gT(e.subject.historyPath,n,o,a)}finally{await Ks(e.subject.historyPath)}throw c}await Ks(e.subject.historyPath);let s=e.nextItem.path??e.currentItem.path;s&&(t=await Ft({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:s,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(s=>{i=()=>{throw s}})}i()},afterWrite:async()=>[...t,...await yT(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function gT(e,t,n,r){t===null?await jc.rm(e,{force:!0}):await ne(e,t);for(let o of n){let a=r.get(o);a===void 0?await jc.rm(o,{force:!0}):await ne(o,a)}}async function yT(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await Y({path:o,scope:"project",op:"history_redact"}));return n.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),n}async function og(e,t,n){let{pmRoot:r,settings:o,typeRegistry:a}=await Sr(n.path),i=t.replacement??"",s=i.length===0,c=s?"[redacted]":i,m=iT(t.literal,t.regex),p=await tn(r,e,o,a.type_to_folder);return La({pmRoot:r,subject:p,settings:o,typeRegistry:a,operation:"history-redact",options:t,transform:u=>wT({pmRoot:r,subject:p,settings:o,typeRegistry:a,options:t,rules:m,replacement:c,replacementIsDefault:s},u)})}function wT(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:a,options:i,rules:s,replacement:c,replacementIsDefault:m}=e,p=t.entries,u=lT(p),f=mT(p,s,c),_=u.hashMismatchesBefore+u.hashMismatchesAfter,h=!!i.dryRun,y=f.replacements>0,g=[];_>0&&g.push(`history_redact_preexisting_hash_mismatches:${_}`),y||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=uT({pmRoot:n,subject:r,settings:o,typeToFolder:a.type_to_folder,finalDocument:f.finalDocument}),S=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),T=t.author,L=fT(i,f),{rewrittenEntries:P,auditEntryAdded:M}=_T({rewritten:f,dryRun:h,changed:y,nextItemDocument:b.document,author:T,message:L});return{changed:y,rewrittenEntries:P,...hT({pmRoot:n,subject:r,settings:o,typeRegistry:a,currentItem:w,nextItem:b,author:T,rewrittenEntries:P}),report:({verification:z,warnings:H})=>({id:r.id,dry_run:h,changed:y,patterns:{literal_count:s.filter(J=>J.kind==="literal").length,regex_count:s.filter(J=>J.kind==="regex").length,total_count:s.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:p.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:M,verify_ok:z.ok,verify_errors:z.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:S},warnings:[...new Set([...g,...H])].sort((J,Z)=>J.localeCompare(Z)),generated_at:k()})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7317758-33fb-52ee-a94b-1b97c4920773")}catch{}})();async function ag(e,t,n){return Bn(e,t,n,{input:await Wa(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Hn(r),createEntry:r=>r,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."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5bdc2e7-1633-5bc8-97c7-8f6ecd253294")}catch{}})();async function ig(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Nt(),o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=C(t.author,a.author_default),s=(await r.resolveValue(t.body,"--body",qu(t,"body"))).trim();if(s.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.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 c=await ce({pmRoot:o,settings:a,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(m){let p=m.body.trim().length>0?`
15
+ `),De.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
16
+ `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),p=cE(m,t);return De.write(`
17
+ `),{prefix:o,preset:s,telemetry_enabled:p}}finally{n.close()}}function _E(e){return{presetFromOption:hh(e.preset),useDefaults:e.defaults===!0,authorFromOption:oE(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:sE(e.agentGuidance),typePreset:rE(e.typePreset)}}function hE(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function gE(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function yE(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(gh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function wE(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=hE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return gE(e.settingsPath,n,e.options.force===!0,e.target),yE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Fe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function vE(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await fE(t,At.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let a=n??"minimal",i=tE();i.id_prefix=t,gh(i,a);let s=ra()?.trim()||void 0;return i.author_default=e.normalizedOptions.authorFromOption??s??"",r!==void 0&&(i.telemetry.enabled=r,i.telemetry.first_run_prompt_completed=!0),await Fe(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function _h(e){return e.settingsExists?await wE(e):await vE({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function bE(e){let t=await Gf({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Fe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function kE(e,t){let n=[],r=[],o=await bp(e,t.schema);for(let a of o.created_paths)n.push(a),r.push(...await Y({path:a,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function SE(e){if(e.typePreset===void 0)return;let t=await mE(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await Y({path:t.file,scope:"project",op:"init:type_preset"})),t}async function EE(e){let t=x(e.settings,O()).folders.filter(r=>!hs.includes(r)),n=await yh(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function AE(e){let t=Q.resolve(e.tracker_root),n=Q.dirname(t);return Q.basename(t)==="pm"&&Q.basename(n)===".agents"?Q.dirname(n):e.workspace_root}async function TE(e,t,n,r){if(!e)return;let o=await Gn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let a=dE(o),i=a.packages.filter(s=>!s.ok).map(s=>s.alias);if(!a.installed_all||i.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,d.GENERIC_FAILURE);return a}function CE(e){let t=r=>Zt([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function IE(e,t,n,r=vf){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function RE(e,t,n,r){if(e==null||n==="status")return;let o=await nc(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Pr(e,t,n={}){let r=t[Oc],o=typeof r=="string"?r:process.cwd(),a=aE(o,t,e,n.workspace),i=a.pmRoot;e=iE(a.prefixArg,n.idPrefix);let s=_E(n);await uE(i,a.target.mode==="tracker-path",n.force===!0);let c=[],m=[],p=Q.join(i,"settings.json"),u=await j(p),f;u&&(f=await _h({pmRoot:i,settingsPath:p,settingsExists:u,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:a.target}));let _=await yh(i,hs);c.push(..._.createdDirs),m.push(..._.warnings),f??=await _h({pmRoot:i,settingsPath:p,settingsExists:u,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:m,target:a.target});let{settings:h}=f,y=AE(a.target),g=await Ca(y??Q.dirname(i)),w=y??g,b=await bE({pmRoot:i,cwd:w??o,agentGuidanceMode:s.agentGuidanceMode,settings:h,warnings:m}),S=await kE(i,h);c.push(...S.createdDirs),m.push(...S.warnings);let T=await SE({pmRoot:i,settings:h,typePreset:s.typePreset,warnings:m});T&&(h=await A(i)),await EE({pmRoot:i,settings:h,createdDirs:c,warnings:m}),await RE(w,i,s.agentGuidanceMode,m),!u&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await IE(i,g,m);let L=await TE(s.installBundledPackages,t,i,m),P=CE({installBundledPackages:s.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:a.target});return{ok:!0,path:i,target:a.target,settings:h,created_dirs:c,warnings:m,governance_preset:h.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...L?{installed_packages:L}:{},next_steps:P,agent_guidance:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ad3dd1-a1ec-5ee8-9f0f-1350dd91f25e")}catch{}})();async function wh(e,t){let n=E(t??process.cwd(),e),r=await A(n);return fe(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="247354d6-fccb-58f8-b969-b1952abf181e")}catch{}})();var OE={"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 vh(e){return Object.fromEntries(Mp.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var bh={ctx:{action:"context"},...OE,...vh("extension"),...vh("package"),...Object.fromEntries(Dp.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="baa27a48-c538-574c-9d05-1f1c0f4f429c")}catch{}})();function kh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xE(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 xc(e,t){let n=xE(t),r=n==="brief"?n:kh(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:kh(e.filters)?e.filters:{},projection:r}}}import{readFile as PE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();function Va(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ie(e,t)}function Sh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Pc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function on(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Hn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=de(n,"--add");return Object.keys(o).map(a=>a.trim().toLowerCase()).some(a=>a!=="text")?n:o.text?.trim()||n}catch{return n}}function Nc(e){return typeof e=="object"&&e!==null&&"code"in e}function Lr(e,t){if(!ft(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function NE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let n=Nt(),r=ft(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Lr(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let o=e.file.trim();if(!o)throw new l("--file path cannot be empty",d.USAGE);if(o==="-")return Lr(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await PE(o,"utf8"),emptyFlag:"--file"}}catch(a){if(Nc(a)&&Wt(a))throw new l(`--file path not found: ${o}. Use --file - to read stdin.`,d.USAGE);let i=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${o}": ${i}. Use --file - to read stdin.`,d.USAGE)}}async function Wa(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await NE(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Nr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Ah(e){return e==="comments"?"--stdin":"--add -"}function LE(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let n=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(n))return;let r=Ah(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${n}" looks like an option, not annotation text. Use ${r} to read stdin, or use text=${n} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${r} for stdin input, pass plain text, or use text=${n} when the text really starts with "-".`,examples:[`${o} ${r}`,`${o} --add text=${n}`]})}function $E(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Ah(e.collectionKey)}`]})}function FE(e,t,n,r,o,a){let i=on(e.metadata,t),s=o?i.findIndex(c=>c.author===n&&c.text===r):-1;return s>=0?{changedFields:[],entryIndex:s+1}:(i.push(a({created_at:k(),author:n,text:r})),e.metadata[t]=i,{changedFields:[t],entryIndex:i.length})}async function Bn(e,t,n,r){$E(r,t);let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=x(a,O()),s=gr(t.limit);if(r.input.mode==="list"){let h=await q(o,e,a.id_prefix,a.item_format,i.type_to_folder);if(!h)throw new l(`Item ${e} not found`,d.NOT_FOUND);let y=await se(h,{schema:a.schema}),g=on(y.document.metadata,r.collectionKey);return Ba(h.id,r.collectionKey,g,s,t.includeMeta===!0)}let c=C(t.author,a.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,y;try{y=await ce({pmRoot:o,settings:a,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=on(w.metadata,r.collectionKey),S=Eh(r.input.index,b.length,r.collectionKey);return Sh(b[S],"deleted"),b.splice(S,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Nr(w,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return Ba(y.item.id,r.collectionKey,g,s,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";LE(m,r);let p=r.parseText(r.input.value??"");if(!p.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let h=r.editOp??r.op,y;try{y=await ce({pmRoot:o,settings:a,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=on(w.metadata,r.collectionKey),S=Eh(r.input.index,b.length,r.collectionKey),T=b[S];return Sh(T,"edited"),b[S]={...T,text:p,edited_at:k()},w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){Nr(w,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return Ba(y.item.id,r.collectionKey,g,s,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:g[r.input.index-1]},t.fullHistory===!0)}let u,f=0;try{u=await ce({pmRoot:o,settings:a,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let y=FE(h,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(h){Nr(h,r.conflictGuidance)}let _=on(u.item,r.collectionKey);return Ba(u.item.id,r.collectionKey,_,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Eh(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,a=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${a})`,d.USAGE)}return e-1}function ME(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Ba(e,t,n,r,o,a,i=!1){let s=a===void 0||i?Pc(n,a!==void 0&&i?void 0:r):a.entry===void 0?[]:[a.entry],c=a!==void 0&&s.length<n.length;return{id:e,[t]:s,count:s.length,...a?.changedCount===void 0?{}:{changed:a.changedCount===1},...[o,a!==void 0].includes(!0)?{total_count:n.length,returned_count:s.length,has_more:c||s.length<n.length,...r!==void 0?{limit:r}:{}}:{},...ME(t,a,c)}}import{readFile as DE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8513dce5-85a0-56aa-bb8f-c64756ac4b2e")}catch{}})();async function Lc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",a=Number(n)+Number(r)+Number(o);if(a===0)return;if(a>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",ft(e))??"",emptyFlag:"--add"};if(r)return Lr(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return Lr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await DE(i,"utf8"),emptyFlag:"--file"}}catch(s){if(Nc(s)&&Wt(s))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let c=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${i}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function UE(e,t){let n=e.edit,r=e.delete,o=n!==void 0,a=r!==void 0;if(o&&a)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(a){if(await Lc(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let s=await Lc(e,t);if(s===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:s.value,emptyFlag:s.emptyFlag}}let i=await Lc(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function Th(e,t,n){let r=Nt(),o=await UE(t,r),a=o.mode==="add"||o.mode==="edit",i=o.value??"";return Bn(e,t,n,{input:{...o,rawValue:t.add??i,value:a?Hn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:s=>s,createEntry:s=>s,bypassOwnershipConflict:!!(o.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(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78e92b9c-f3da-594e-8158-00409222308f")}catch{}})();var Ch=new Set(["item_format"]),Ih=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),GE=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),jE=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),qE={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function KE(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Ch.has(t)||Ih.has(t)||GE.has(t)||t==="context")return t}function zE(e){let t=e.trim().toLowerCase();return qE[t]??e}function Rh(e,t){let n=KE(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:Ch.has(n)?{routable:!0,flag:"format",value:t}:Ih.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:jE.has(n)?zE(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="544840da-22f5-5734-81ec-e12c5612545c")}catch{}})();var HE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Oh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>128)throw new Error("A legacy author must contain 1-128 characters.");return t}function BE(e){let t=e?.trim().toLowerCase();if(!t||!HE.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function VE(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function WE(e,t){let n=new Set;for(let r of(e??[]).slice(0,1e4)){let o=r.trim().slice(0,128);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function YE(e,t){let n=Oh(t.legacy_author),r=BE(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function JE(e,t){if(t.operation==="add")return YE(e,t);if(t.operation==="remove"){let r=Oh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function $c(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function xh(e,t){let n=e?.version??1,r={...e?.aliases},o=JE(r,t),a={version:o?n+1:n,aliases:VE(r)};return{vocabulary:a,preview:{operation:t.operation,changed:o,version_before:n,version_after:a.version,alias_count:Object.keys(a.aliases).length,residual_author_count:WE(t.observed_authors,a.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d9b6f2ba-2c5e-52ea-891d-53124601fb89")}catch{}})();var Ph=["project","global"],yt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},XE=Object.keys(yt).map(e=>yt[e][0]),QE=Object.fromEntries(Object.keys(yt).flatMap(e=>yt[e].map(t=>[t,e]))),ZE={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},eA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],tA=new Set(["metadata_required_fields",...eA]),nA=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),rA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),oA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),aA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),iA=new Set(["governance_preset","governance_create_default_type"]),Mh=e=>tA.has(e),sA=e=>oA.has(e),cA=e=>aA.has(e),lA=e=>iA.has(e);function Fc(e){return e==="definition_of_done"||Mh(e)}function dA(e){if(Ph.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${Ph.join(", ")}`,d.USAGE)}function mA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Ce({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function pA(e){let t=QE[e];if(t)return t;let n=Es.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${XE.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function uA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function fA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function Dh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function _A(e){return Dc(e,"test-result-tracking")}function Dc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Uh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Uc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function Gh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function jh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function qh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function Kh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function zh(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function Hh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function Bh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}var hA={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Nh(e,t){let n=hA[e];if(n)return Dc(t,n);switch(e){case"history_missing_stream_policy":return Dh(t);case"sprint_release_format_policy":return Qs(t);case"parent_reference_policy":case"governance_parent_reference_policy":return ga(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Uc(t);case"governance_preset":return Gh(t);case"governance_ownership_enforcement":return jh(t);case"governance_create_mode_default":return qh(t);case"governance_close_validation_default":return Kh(t);case"governance_require_close_reason":return Bh(t);case"governance_workflow_enforcement":return zh(t);case"governance_force_required_for_stale_lock":return Hh(t);case"telemetry_tracking":return Uh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Lh={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},gA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function yA(e,t){let n=[...new Set((e??[]).map(a=>a.trim()).filter(a=>a.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(a=>a.toLowerCase().replaceAll("-","_")),o=r.filter(a=>Lh[a]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${gA.join(", ")}`,d.USAGE);return[...new Set(r.map(a=>Lh[a]))].sort((a,i)=>a.localeCompare(i))}function wA(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,a)=>o.localeCompare(a));if(n){if(r.length>0)throw new l(`Config set ${yt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${yt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function vA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function bA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return pA(t)}function Vh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var kA={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>$c(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Gc(e,t){return kA[t](e)}function Re(e,t){return t.length===0?e:{...e,warnings:t}}async function SA(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):lt(n),o=re(r);return e==="project"&&await I(r),{pmRoot:r,settingsPath:o}}function EA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function $h(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function AA(e,t,n,r,o){let a=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!_s.includes(c))throw new l(`Context --default-depth must be one of ${_s.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,a=!0)}if(t.activityLimit!==void 0){let c=$h(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,a=!0)}if(t.staleThresholdDays!==void 0){let c=$h(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,a=!0)}let s=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of s){let p=EA(m);if(p!==void 0){let u=c;i.sections[u]!==p&&(i.sections[u]=p,a=!0)}}return a&&await Fe(n.pmRoot,e,"config:set:context"),Re({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:a},o)}function TA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function CA(e,t,n,r,o,a){if(o===void 0)return a;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return TA(t,o,a);Vh(n);let i=Rh(n,o);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(a.criterion!==void 0&&a.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...a,criterion:i.values}}if(i.flag==="format")return{...a,format:i.value};if(a.policy!==void 0&&Nh(n,a.policy)!==Nh(n,i.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${a.policy}". Pass only one.`,d.USAGE);return{...a,policy:i.value}}function IA(e){let t=Object.keys(yt).map(r=>({key:r,aliases:yt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Fc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Fc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:ZE[r],value:Gc(e.settings,r)})),n=Es.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:As(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Re({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function RA(e){let t=Object.fromEntries(Object.keys(yt).map(n=>[n,Gc(e.settings,n)]));return Re({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function OA(e,t){let n=Gc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Re({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Re({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Re({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Re({...r,criteria:n},e.warnings):Re({...r,policy:n},e.warnings)}async function xA(e,t,n,r){if(t==="get"){let s=As(e.settings,n);return Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let a=Tp(n,o);if(!a.ok)throw new l(a.error.message,d.USAGE);let i=Vo(e.settings,n,a.parsed.value);return i&&await Fe(e.target.pmRoot,e.settings,`config:set:${n.path}`),Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function Z(e,t,n){t&&await Fe(e.target.pmRoot,e.settings,n)}function Fh(e,t,n){return e!==n||t!==n}function me(e,t,n,r){return Re({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Mc(e,t,n,r){return Re({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function PA(e,t){let n=fA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let a=x(e.settings,O()),i=await nf(e.target.pmRoot,n,"config:set:item_format:migrate",a.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Fe(e.target.pmRoot,e.settings,"config:set:item_format")}return Re({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function NA(e,t,n){if(t==="history_missing_stream_policy"){let a=Dh(n.policy),i=e.settings.history.missing_stream!==a;return e.settings.history.missing_stream=a,await Z(e,i,"config:set:history_missing_stream_policy"),me(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let a=Qs(n.policy),i=e.settings.validation.sprint_release_format!==a;return e.settings.validation.sprint_release_format=a,await Z(e,i,"config:set:sprint_release_format_policy"),me(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let a=ga(n.policy),i=e.settings.validation.parent_reference!==a||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==a;return e.settings.validation.parent_reference=a,e.settings.governance.preset="custom",e.settings.governance.parent_reference=a,await Z(e,i,"config:set:parent_reference_policy"),me(e,t,e.settings.validation.parent_reference,i)}let r=Uc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Z(e,o,"config:set:metadata_validation_profile"),me(e,t,e.settings.validation.metadata_profile,o)}async function LA(e,t,n){if(t==="metadata_required_fields"){let i=yA(n.criterion,n.clearCriteria),s=i.length!==e.settings.validation.metadata_required_fields.length||i.some((c,m)=>c!==e.settings.validation.metadata_required_fields[m]);return e.settings.validation.metadata_required_fields=i,await Z(e,s,"config:set:metadata_required_fields"),Mc(e,t,[...e.settings.validation.metadata_required_fields],s)}let r={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=wA(t,n.criterion,n.clearCriteria),a=o.length!==r.length||o.some((i,s)=>i!==r[s]);return r.splice(0,r.length,...o),await Z(e,a,`config:set:${t}`),Mc(e,t,[...r],a)}async function $A(e,t,n){if(t==="governance_preset"){let c=Gh(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Z(e,m,"config:set:governance_preset"),me(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Z(e,c,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let a=x(e.settings,O()),i=be(o,a);if(!i)throw new l(Rt(o,a.types,Ot(e.target.pmRoot,e.settings.schema)),d.USAGE);let s=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await Z(e,s,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type,s)}async function FA(e,t,n){if(t==="governance_ownership_enforcement"){let a=jh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==a;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=a,await Z(e,i,"config:set:governance_ownership_enforcement"),me(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let a=qh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==a;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=a,await Z(e,i,"config:set:governance_create_mode_default"),me(e,t,e.settings.governance.create_mode_default,i)}let r=Kh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Z(e,o,"config:set:governance_close_validation_default"),me(e,t,e.settings.governance.close_validation_default,o)}async function MA(e,t,n){if(t==="governance_parent_reference_policy"){let a=ga(n.policy),i=e.settings.governance.preset!=="custom"||Fh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,a);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=a,e.settings.validation.parent_reference=a,await Z(e,i,"config:set:governance_parent_reference_policy"),me(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let a=Uc(n.policy),i=e.settings.governance.preset!=="custom"||Fh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,a);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=a,e.settings.validation.metadata_profile=a,await Z(e,i,"config:set:governance_metadata_validation_profile"),me(e,t,e.settings.governance.metadata_profile,i)}let r=zh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Z(e,o,"config:set:governance_workflow_enforcement"),me(e,t,e.settings.governance.workflow_enforcement,o)}async function DA(e,t,n){if(t==="governance_require_close_reason"){let a=Bh(n.policy)==="enabled",i=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Z(e,i,"config:set:governance_require_close_reason"),me(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",i)}let r=Hh(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==r;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=r,await Z(e,o,"config:set:governance_force_required_for_stale_lock"),me(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function UA(e,t,n){if(t==="test_result_tracking"){let a=_A(n.policy)==="enabled",i=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Z(e,i,"config:set:test_result_tracking"),me(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",i)}if(t==="untrusted_linked_test_execution"){let a=Dc(n.policy,"untrusted-linked-test-execution")==="enabled",i=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Z(e,i,"config:set:untrusted_linked_test_execution"),me(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",i)}let r=Uh(n.policy)==="enabled",o=e.settings.telemetry.enabled!==r||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=r,e.settings.telemetry.first_run_prompt_completed=!0,await Z(e,o,"config:set:telemetry_tracking"),me(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function GA(e,t,n){let r=uA(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((a,i)=>a!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await Z(e,o,"config:set:definition_of_done"),Mc(e,t,[...e.settings.workflow.definition_of_done],o)}function jA(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function qA(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function KA(e,t){let{operation:n,dryRun:r}=jA(t.policy),o=qA(n,t.value),a;try{a=xh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new l(i.message,d.USAGE)}return a.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:a.vocabulary},await Z(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${a.preview.version_after}`)),Re({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:$c(r?e.settings.agent_identity?.identity_vocabulary:a.vocabulary),vocabulary_mutation:a.preview,settings_path:e.target.settingsPath,changed:a.preview.changed&&!r},e.warnings)}async function zA(e,t,n){if(n.clearCriteria===!0&&!Fc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?PA(e,n):t==="context"?AA(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?KA(e,n):t==="definition_of_done"?GA(e,t,n):Mh(t)?LA(e,t,n):nA.has(t)?UA(e,t,n):rA.has(t)?DA(e,t,n):sA(t)?FA(e,t,n):cA(t)?MA(e,t,n):lA(t)?$A(e,t,n):NA(e,t,n)}async function Wh(e,t,n,r,o,a){let i=dA(e),s=mA(t),c=s==="get"||s==="set"?Bo(n):void 0,m=c?void 0:bA(s,n),p=CA(s,n,m,c,a,r),u=await SA(i,o),{settings:f,metadata:_,warnings:h}=await Uu(u.pmRoot),y={scope:i,target:u,settings:f,metadata:_,warnings:vA(h)};return c?xA(y,s,c,p):s==="list"?IA(y):s==="export"?RA(y):(Vh(m),s==="get"?OA(y,m):zA(y,m,p))}import Jh from"node:fs/promises";import Xh from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function HA(e,t,n){let r=new Set,o=[];for(let a of e){let i=a.trim();if(i.length===0||r.has(i))continue;r.add(i);let s=t.get(i);if(s===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(s.entries<=n){o.push({id:i,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:s.entries,selected:!0,skip_reason:null})}return o}function BA(e,t){let n=[...e].sort((o,a)=>a.entries-o.entries||o.id.localeCompare(a.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Yh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return HA(t.ids,n,t.minEntries)}return BA(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6009e5f-840e-5e3a-b8b9-6e9d42d63410")}catch{}})();function VA(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let a=Number.parseInt(n,10),i=Mn(t);if(!Number.isSafeInteger(a)||a<i+1||a>i+t.length+1)throw new l(`history-compact --before version must be between ${i+1} and ${i+t.length+1}.`,d.USAGE);let s=a-i-1;return{kind:"version",raw:n,compactCount:s,retainedCount:t.length-s}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let o=0;for(let[a,i]of t.entries()){let s=Date.parse(i.ts);if(!Number.isFinite(s))throw new l(`History for this item contains invalid timestamp at entry ${a+1}.`,d.GENERIC_FAILURE);if(s>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function WA(e,t){let n=ur(),r=ur();for(let o=0;o<e.length;o+=1){let a=e[o];n=Dn(n,a.patch,o+1,a.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function YA(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Iu.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Bs(_r(e.document),r,ut(n.hash_algorithm)).includes(n.after_hash))}}function JA(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function XA(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function QA(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=WA(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Mn(e.historyEntries,!0),a=e.historyEntries[e.boundary.compactCount-1],i=$e({hashAlgorithm:ut(a.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:ot(ur()),after:ot(t),message:XA(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:Ru(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),s=[Ou({...i,before_hash:Bs(ur(),a.item_hash_version??1,ut(a.hash_algorithm))[0],after_hash:a.after_hash,item_hash_version:a.item_hash_version}),...r];return e.dryRun||s.push($e({nowIso:k(),author:e.author,op:"history_compact",before:ot(n),after:ot(n),message:JA(e.options,e.boundary)})),{rewrittenEntries:s,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function jc(e,t,n){let{pmRoot:r,settings:o,typeRegistry:a}=await kr(n.path),i=await tn(r,e,o,a.type_to_folder);return $a({pmRoot:r,subject:i,settings:o,typeRegistry:a,operation:"history-compact",options:t,transform:s=>ZA(i,t,s)})}function ZA(e,t,n){let r=e.historyPath,o=n.entries,a=n.verification;if(!a.ok)throw new l(`history-compact requires a valid history chain (${a.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);let i=VA(t.before,o),s=i.compactCount>0,c=!!t.dryRun,m=n.author,p=[];s||p.push("history_compact_noop_before_boundary");let u=YA(n.loadedItem,o);u.matchedChainBefore===!1&&p.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:h}=QA({historyEntries:o,boundary:i,changed:s,dryRun:c,author:m,options:t}),y=Mn(o,!0),g=i.retainedCount>0&&y!==null?y+i.compactCount+1:null;return{changed:s,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:c,changed:s,compact_boundary:{kind:i.kind,before:i.raw,entries_compacted:i.compactCount,entries_retained:i.retainedCount,first_retained_entry:g},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:h,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...p,...b])].sort((S,T)=>S.localeCompare(T)),generated_at:k()})}}var eT=3;function tT(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,d.USAGE)}let t=ha(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:_a(t)}}function Qh(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)==0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function nT(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function rT(e){let t=$(e.settings.schema),n=Sa(t),r=await fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),a=Xh.join(e.pmRoot,"history"),i=[],s=[];if(!await j(a))return{candidates:i,preselectionErrors:s};let c=(await Jh.readdir(a)).filter(m=>m.endsWith(".jsonl")).sort((m,p)=>m.localeCompare(p));for(let m of c){let p=Xh.join(a,m),u=m.slice(0,-6);try{let f=await Jh.readFile(p,"utf8");await Rn({path:p,scope:"project"}),i.push({id:u,entries:nT(f),bucket:o.get(u)??null})}catch(f){s.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:s}}async function oT(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await jc(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function Zh(e,t){let n=tT(e),{pmRoot:r,settings:o,typeRegistry:a}=await kr(t.path),{candidates:i,preselectionErrors:s}=await rT({pmRoot:r,settings:o,typeToFolder:a.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??eT,p=o.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&p.enabled,f=e.allOver??(u?p.max_entries:void 0),_=Yh(i,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),h=!!e.dryRun,y=[...s],g={streams_considered:i.length+s.length,selected:0,items_compacted:0,items_skipped:0,items_errored:s.length};for(let w of _){let b=await oT({row:w,options:n,dryRun:h,global:t});if(y.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:h,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:u},totals:g,results:y,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="feb8c44f-a6bd-5a7e-9600-eb5c45c0a5b4")}catch{}})();function eg(e){let t=e.options.all===!0,n=e.id??v(e.options,"id");return h_(n,t),t?Fa(e.options,e.global):Ut(n,e.options,e.global)}function tg(e){let t=e.options.ids,n=ha(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.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 r=n===void 0?void 0:_a(n),o=Me(e.options.allOver??e.options.all_over,"history-compact allOver"),a=Me(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),i=v(e.options,"scope"),s=[];e.options.closed===!0&&s.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&s.push("all-streams"),(i==="closed"||i==="all-streams")&&s.push(i);let c=[...new Set(s)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return Qh(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?jc(e.id,{before:v(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global):Zh({ids:r,scope:m,allOver:o,minEntries:a,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:v(e.options,"author"),message:v(e.options,"message"),force:e.force},e.global)}import qc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebf3254f-1fed-5972-b91a-b8ff101675f4")}catch{}})();function ng(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function aT(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function iT(e){let t=e.trim();if(t.length===0)throw new l("history-redact --regex requires a non-empty pattern.",d.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=aT(t.slice(o+1)))}if(n.length===0)throw new l("history-redact --regex cannot use an empty pattern.",d.USAGE);try{new RegExp(n,r)}catch{throw new l("Invalid --regex value; provide a valid JavaScript regular expression.",d.USAGE)}return{kind:"regex",source:n,flags:r}}function sT(e,t){let n=[...new Set(ng(e).map(a=>a.trim()))].filter(a=>a.length>0).map(a=>({kind:"literal",value:a})),r=[...new Set(ng(t).map(a=>a.trim()))].filter(a=>a.length>0).map(iT),o=[...n,...r];if(o.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",d.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function cT(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let a=e.indexOf(t,r);if(a===-1)break;o+=1,r=a+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function lT(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function og(e,t,n){let r=e,o=0;for(let a of t){let i=a.kind==="literal"?cT(r,a.value,n):lT(r,a,n);r=i.value,o+=i.replacements}return{value:r,replacements:o}}function Ya(e,t,n){if(typeof e=="string")return og(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(o=>{let a=Ya(o,t,n);return r+=a.replacements,a.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[a,i]of Object.entries(e)){let s=Ya(i,t,n);r+=s.replacements,o[a]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function rg(e,t,n){let r=0;return{patch:e.map(o=>{if(!Object.prototype.hasOwnProperty.call(o,"value"))return o;let a=Ya(o.value,t,n);return r+=a.replacements,a.replacements>0?{...o,value:a.value}:o}),replacements:r}}function dT(e){let t=structuredClone(Hs),n=0,r=0;for(let o=0;o<e.length;o+=1){let a=e[o];fr(t,void 0,ut(a.hash_algorithm))!==a.before_hash&&(n+=1),t=Dn(t,a.patch,o+1,a.op),fr(t,void 0,ut(a.hash_algorithm))!==a.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function mT(e,t,n){let r=0,o=!1,a=!1,i=e.message;if(typeof e.message=="string"){let m=og(e.message,t,n);i=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let s=rg(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;let c=e.reanchor_evidence?.map(m=>{let p=m.patch?rg(m.patch,t,n):{patch:void 0,replacements:0},u=m.record?Ya(m.record,t,n):{value:void 0,replacements:0};r+=p.replacements,r+=u.replacements;let f=p.replacements>0||u.replacements>0;if(o||=f,!f)return m;a=!0;let{patch:_,record:h,record_hash:y,record_hash_version:g,...w}=m;return p.replacements>0?w:{...w,patch:m.patch}});return{entry:{...e,message:i,patch:s.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:a}}function pT(e,t,n){let r=structuredClone(Hs),o=0,a=0,i=[];for(let s=0;s<e.length;s+=1){let c=e[s],m=xu(c);if(!m.ok)throw new l(`history-redact refuses invalid immutable record ${s+1} (${m.error}).`,d.GENERIC_FAILURE);let p=mT(c,t,n);a+=p.replacements,p.changed&&(o+=1);let u=fr(r,void 0,ut(c.hash_algorithm));r=Dn(r,p.entry.patch,s+1,p.entry.op);let f=fr(r,void 0,ut(c.hash_algorithm));i.push(Pu(c,{...p.entry,before_hash:u,after_hash:f},{retainPriorRecord:p.changed,retainPriorRecordHash:!p.changed}))}return{entries:i,finalDocument:r,entriesChanged:o,replacements:a}}function uT(e){return Object.keys(e.metadata).length>0}function fT(e){if(!uT(e.finalDocument))return{raw:null,path:null,document:null};let t=rt(ot(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",d.USAGE);return{document:t,path:dt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Be(t,{format:"toon",schema:e.settings.schema})}}function _T(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function hT(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??ot(e.rewritten.finalDocument);return t.push($e({nowIso:k(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function gT(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await $t(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let a=new Map;e.currentItem.path&&e.currentItem.raw!==null&&a.set(e.currentItem.path,e.currentItem.raw);let i=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await ne(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await qc.rm(e.currentItem.path,{force:!0}),await ne(e.subject.historyPath,Lu(e.rewrittenEntries))}catch(c){try{await yT(e.subject.historyPath,n,o,a)}finally{await zs(e.subject.historyPath)}throw c}await zs(e.subject.historyPath);let s=e.nextItem.path??e.currentItem.path;s&&(t=await Ft({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:s,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(s=>{i=()=>{throw s}})}i()},afterWrite:async()=>[...t,...await wT(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function yT(e,t,n,r){t===null?await qc.rm(e,{force:!0}):await ne(e,t);for(let o of n){let a=r.get(o);a===void 0?await qc.rm(o,{force:!0}):await ne(o,a)}}async function wT(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await Y({path:o,scope:"project",op:"history_redact"}));return n.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),n}async function ag(e,t,n){let{pmRoot:r,settings:o,typeRegistry:a}=await kr(n.path),i=t.replacement??"",s=i.length===0,c=s?"[redacted]":i,m=sT(t.literal,t.regex),p=await tn(r,e,o,a.type_to_folder);return $a({pmRoot:r,subject:p,settings:o,typeRegistry:a,operation:"history-redact",options:t,transform:u=>vT({pmRoot:r,subject:p,settings:o,typeRegistry:a,options:t,rules:m,replacement:c,replacementIsDefault:s},u)})}function vT(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:a,options:i,rules:s,replacement:c,replacementIsDefault:m}=e,p=t.entries,u=dT(p),f=pT(p,s,c),_=u.hashMismatchesBefore+u.hashMismatchesAfter,h=!!i.dryRun,y=f.replacements>0,g=[];_>0&&g.push(`history_redact_preexisting_hash_mismatches:${_}`),y||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=fT({pmRoot:n,subject:r,settings:o,typeToFolder:a.type_to_folder,finalDocument:f.finalDocument}),S=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),T=t.author,L=_T(i,f),{rewrittenEntries:P,auditEntryAdded:M}=hT({rewritten:f,dryRun:h,changed:y,nextItemDocument:b.document,author:T,message:L});return{changed:y,rewrittenEntries:P,...gT({pmRoot:n,subject:r,settings:o,typeRegistry:a,currentItem:w,nextItem:b,author:T,rewrittenEntries:P}),report:({verification:z,warnings:H})=>({id:r.id,dry_run:h,changed:y,patterns:{literal_count:s.filter(J=>J.kind==="literal").length,regex_count:s.filter(J=>J.kind==="regex").length,total_count:s.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:p.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:M,verify_ok:z.ok,verify_errors:z.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:S},warnings:[...new Set([...g,...H])].sort((J,ee)=>J.localeCompare(ee)),generated_at:k()})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7317758-33fb-52ee-a94b-1b97c4920773")}catch{}})();async function ig(e,t,n){return Bn(e,t,n,{input:await Wa(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Hn(r),createEntry:r=>r,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."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5bdc2e7-1633-5bc8-97c7-8f6ecd253294")}catch{}})();async function sg(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Nt(),o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=C(t.author,a.author_default),s=(await r.resolveValue(t.body,"--body",qu(t,"body"))).trim();if(s.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.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 c=await ce({pmRoot:o,settings:a,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(m){let p=m.body.trim().length>0?`
17
18
 
18
19
  `:"";return m.body=`${m.body.trimEnd()}${p}${s}
19
- `,{changedFields:["body"]}}});return{item:c.item,appended:s,changed_fields:c.changedFields}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f7d8635-ea1c-5c87-9001-bfa1d1618478")}catch{}})();var vT=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function sg(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function qc(e,t){return Kc(e,t,{operation:"close"})}function Kc(e,t,n){let r=sg(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function zc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],a=o.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,s=[];if(r&&(delete e.blocked_by,s.push("blocked_by")),i&&(delete e.blocked_reason,s.push("blocked_reason")),t.orderingEdges==="remove"&&a.length>0){let m=new Set(a),p=o.filter(u=>!m.has(u));p.length>0?e.dependencies=p:delete e.dependencies,s.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:s,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...a.length>0?[`closed_removed_predecessors:${e.id}:${a.map(m=>m.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${a.length}`]:[]]};let c=[...new Set([...n?[n]:[],...a.map(m=>m.id)])];return c.length===0?{changedFields:s,warnings:[]}:{changedFields:s,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab15186d-b8bc-5740-bc16-d5af1eeeaa02")}catch{}})();var bT=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function kT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function cg(e){let t=[];for(let n of bT){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function lg(e,t,n={}){let r=cg(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},a=r.map(s=>`--${s.key.replaceAll("_","-")}`),i=["--pm-path",t,"update",e.id,...r.flatMap((s,c)=>[a[c],o[s.key]?.trim()||"<value>"])];return{missing:a,suggested_retry:Zt(i),suggested_retry_args:i}}async function ST(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let a=o.trim();if(a===n)return!0;if(r.has(a))return!1;r.add(a),o=(await e(a))?.duplicate_of}return!1}function ET(e){return typeof e!="string"||e.trim().length===0}async function AT(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let a=x(t,O()),i=new Map,s=async m=>{if(i.has(m))return i.get(m)??null;let p=await q(e,m,t.id_prefix,t.item_format,a.type_to_folder);if(!p)return i.set(m,null),null;let{document:u}=await se(p,{schema:t.schema});return i.set(m,u.metadata),u.metadata},c=await s(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,d.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await ST(s,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,d.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function TT(e,t,n){return e.filter(r=>r.parent===t&&!oe(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function CT(e,t,n){let r=new Map(e.map(s=>[s.id.trim().toLowerCase(),s])),o=af(e),a=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(s=>i.has(s.status)).map(s=>({item:s,blockerIds:o.get(s.id.trim().toLowerCase())})).filter(({blockerIds:s})=>s.includes(a)).filter(({blockerIds:s})=>s.every(c=>{if(c===a)return!0;let m=r.get(c);return m!==void 0&&oe(m.status,n)})).map(({item:s,blockerIds:c})=>({id:s.id,blocker_ids:c})).sort((s,c)=>s.id.localeCompare(c.id))}async function IT(e,t,n,r,o,a){let i=CT(n,r,a),s=[];for(let c of i)try{let m=await ce({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(p){let u=p.metadata.dependencies??[],f=u.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});p.metadata.status=a.open_status,delete p.metadata.blocked_by,delete p.metadata.blocked_reason,p.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?p.metadata.dependencies=f:delete p.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==u.length&&_.push("dependencies"),{changedFields:_}}});s.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let p=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";s.push(`auto_unblock_failed:${c.id}:${p}`)}return s}function RT(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:a}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[a]=i,n.push(a))}return n}function OT(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:a}of r)ET(e[o])&&(e[o]=a,n.push(o));return n}function xT(e,t,n,r){let o=[];if(t!=="off"){let a=cg(e);if(a.length>0){let i=a.map(s=>s.label);if(t==="strict"){let s=a.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...s.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:s,suggested_retry:Zt(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function PT(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function NT(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function LT(e,t){if(oe(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,d.CONFLICT,{recovery:lg(e,t.pmRoot,t.options)});let n=RT(e,t.options),r=OT(e,t.duplicateOf),o=xT(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let a=t.options.completedAt!==void 0||e.completed_at===void 0;a&&(e.completed_at=t.completedAt);let i=["status","closed_at",...a?["completed_at"]:[],...PT(e,t.closeReason),...n];if(rf(e)&&(e.plan_mode="completed",i.push("plan_mode")),t.duplicateOf!==void 0){i.push("duplicate_of");for(let c of r)i.includes(c)||i.push(c)}i.push(...NT(e));let s=zc(e,t.lifecyclePolicy);return i.push(...s.changedFields),o.push(...s.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function dg(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let a=await A(o),i=$(a.schema),s=C(n.author,a.author_default),c=x(a,O()).type_to_folder,m=await q(o,e,a.id_prefix,a.item_format,c);if(!m)throw await _t(o,e,a.id_prefix,c);let p=await AT(o,a,n.duplicateOf,m.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??a.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=qc({explicit:t,duplicateOf:p,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,_=kT(n.validateClose)??a.governance.close_validation_default,h=await fe(o,a.item_format,c,void 0,a.schema),y=TT(h,m.id,i),g=k(),w=n.completedAt===void 0?g:ie(n.completedAt,new Date(g),"completed-at"),b=await ce({pmRoot:o,settings:a,id:m.id,op:"close",author:s,message:n.message,force:n.force,mutate(T){return LT(T.metadata,{pmRoot:o,statusRegistry:i,force:n.force,options:n,duplicateOf:p,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:w,lifecyclePolicy:u})}}),S=_==="warn"?lg(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...S?{recovery:S}:{},warnings:[...b.warnings,...await IT(o,a,h,m.id,s,i)]}}function wt(e,t,n,r){return dg(e,t,n,r)}import $T from"fast-json-patch";import Hc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebfa0c5e-461b-5078-8272-69086e84b4dc")}catch{}})();async function mg(e,t,n){let r=await Xu(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:pg(n),recovered:!0}}function FT(e,t){return Wu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function pg(e){let t=Xs(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:nt(rt(t))}async function MT(e,t,n,r){let o=await tn(e,t,n,r),a=o.located?await Ku({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:a.warnings}}function DT(e,t){let n=hr(e),r=hr(t),o=$T.compare(n,r),a=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){a.add("body");continue}let s=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];a.add(s.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(a).sort((i,s)=>i.localeCompare(s))}async function UT(e){let t=await u_({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>mg(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function GT(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:pg(t),originalRaw:null}}function jT(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function qT(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ne(e.existingItemPath,e.resolvedOriginalRaw),await Hc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ne(e.existingItemPath,e.resolvedOriginalRaw);return}await Hc.rm(e.restoredItemPath,{force:!0})}async function KT(e){return[...await Y({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Y({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function an(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let a=await A(o),i=x(a,O()),s=await MT(o,e,a,i.type_to_folder),c=s.id,{raw:m,entries:p}=await Su(s.historyPath,c);if(p.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let u=FT(t,p),f=Yu(Xs(p,u.historyIndex),u),_=Pu(f,{schema:a.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let h=(s.located?await mg(s.located,a,p):null)?.raw??null,y=C(n.author,a.author_default),g=await Te(o,c,a.locks.ttl_seconds,y,!!n.force,a.governance.force_required_for_stale_lock,a.locks.wait_ms);try{let{loadedItemUnderLock:w,existingItemPath:b}=await UT({pmRoot:o,subject:s,settings:a,typeRegistry:i,historyRawBeforeLock:m,currentItemRawBeforeLock:h,history:p}),S="toon",T=GT(w,p),L=jT({document:T.document,author:y,force:n.force,enforcement:a.governance.ownership_enforcement,resolvedId:c}),P=DT(T.document,_),M=await wr({pmRoot:o,settings:a,operation:"restore",author:y,before:T.document,after:_});await Wo({pm_root:o,operation:"restore",before:T.document,after:_,changed_fields:P,sdk:ka({pmRoot:o,settings:a,typeToFolder:i.type_to_folder})});let z=Be(_,{format:S,schema:a.schema}),H=dt(o,_.metadata.type,c,S,i.type_to_folder),J=await $t(o,y),Z=[];try{await ne(H,z),b&&H!==b&&await Hc.rm(b);let pe=Le({nowIso:k(),author:y,op:"restore",before:T.document,after:_,message:n.message,context:M.decisions.length===0?void 0:{workflow_policies:M.decisions}});try{await xt(s.historyPath,pe)}catch(Qe){throw await qT({existingItemPath:b,resolvedOriginalRaw:T.originalRaw,restoredItemPath:H}),Qe}Z=await Ft({pmRoot:o,preferredFormat:a.item_format,typeToFolder:i.type_to_folder,schema:a.schema,itemPath:H,previousItemPath:b??void 0,document:_})}finally{await J()}let Ee=await KT({restoredItemPath:H,historyPath:s.historyPath,before:T.document,after:_});In({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:T.document.metadata.status,status:_.metadata.status,previous:Qt(T.document.metadata,P),current:Qt(_.metadata,P),changed_fields:P});let Xe=p[u.historyIndex],G=Mn(p,!0);return{item:_.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:G===null?null:G+u.historyIndex+1,entry_ts:Xe.ts,entry_op:Xe.op},changed_fields:P,warnings:[...M.warnings,...w?.recovered?["restore_unreadable_item_recovered"]:[],...s.historyPolicyWarnings,...L,...Z,...Ee]}}finally{await g()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6edfa77d-9b76-540b-a365-a3fef0450c53")}catch{}})();var fg=1,Bc="close-many",zT=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function HT(e,t){return Ir(e,t,{includePagination:!1})}function BT(e,t){return Ir(e,t)}function VT(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function WT(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function YT(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.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 JT(e,t){let n=$(t.schema),r=x(t,O()),o=await fe(e,t.item_format,r.type_to_folder,void 0,t.schema),a=new Map,i=new Map;for(let s of o){if(typeof s.parent!="string"||s.parent.length===0||(i.set(s.id,s.parent),oe(s.status,n)))continue;let c=a.get(s.parent);c?c.push(s.id):a.set(s.parent,[s.id])}for(let s of a.values())s.sort((c,m)=>c.localeCompare(m));return{childrenByParent:a,parentByChild:i}}function ug(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,a=t.get(e),i=[],s=new Set,c=!1;for(;a!==void 0&&!s.has(a);){let m=n?.get(a);if(m!==void 0){o+=m+1;break}s.add(a),i.push(a),o+=1,a=t.get(a)}if(a!==void 0&&s.has(a)&&(c=!0),!c){n?.set(e,o);for(let[m,p]of i.entries())n?.set(p,o-m-1)}return o}async function XT(e){let t=await ca(e.pmRoot,Bc,e.rollbackId,fg),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await la(t.items,(o,a)=>an(o,a,{author:e.options.author,message:n,force:!0},e.global));return{...en({applied:r.restored_ids.length,skipped:0,failed:r.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:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function QT(e,t,n,r,o){return e.map(a=>{let i=(t.get(a.id)??[]).filter(c=>!n.has(c)),s=!_g(a,r,o);return{id:a.id,title:typeof a.title=="string"?a.title:"",status:a.status,action:s?"skip":"close",...s?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function ZT(e){let t=await sa(e.pmRoot,Bc,e.checkpointId,{schema_version:fg,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 eC(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await wt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:An(o)})}}return{rows:t,closedIds:n}}function tC(e){return typeof e.rollback=="string"?e.rollback:void 0}function nC(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(BT(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function rC(e){if(!HT(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${zT}). Refusing to match every item.`,d.USAGE)}function oC(e,t){let n=new Map;return[...e].sort((r,o)=>{let a=ug(o.id,t,n)-ug(r.id,t,n);return a!==0?a:r.id.localeCompare(o.id)})}function _g(e,t,n){return n||!oe(e.status,t)}function aC(e,t,n){return new Set(e.filter(r=>_g(r,t,n)).map(r=>r.id))}async function iC(e){rC(e.options);let t=$(e.settings.schema),n=YT(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ht(e.options.status,WT(e.options.list),e.global),{childrenByParent:a,parentByChild:i}=await JT(e.pmRoot,e.settings),s=oC(o.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await ht(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,p=new Set(m.map(f=>f.id)),u=aC(s,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:s,unmatchedIds:c.length===0?void 0:c.filter(f=>!p.has(f)),planRows:QT(s,a,u,t,r)}}function sC(e){return{outcome:"effect",exit_code:d.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 cC(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 ZT({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 hg(e,t){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=e.dryRun===!0,a=tC(e);if(VT(e.list),a!==void 0)return nC(e,a),XT({pmRoot:n,rollbackId:a,options:e,global:t});let i=await iC({pmRoot:n,settings:r,options:e,global:t});if(o)return sC(i);let s=new Set(i.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=k(),m=ia(Bc,c),p=await cC({context:i,options:e,closableIds:s,checkpointId:m,nowValue:c}),u={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await eC({matched:i.matched,closableIds:s,reason:i.reason,closeOptions:u,global:t}),h=f.filter(w=>w.status==="closed").length,y=f.filter(w=>w.status==="skipped").length,g=f.filter(w=>w.status==="failed").length;return{...en({applied:h,skipped:y,failed:g,unmatched:i.unmatchedIds?.length??0}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...p?{checkpoint:p}:{},closed_count:h,skipped_count:y,failed_count:g,rows:f,ids:_,...i.unmatchedIds!==void 0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="902e9f78-a2c1-59bb-aaa2-763576d5c68b")}catch{}})();function lC(e,t){return[...new Set([...so.filter(n=>e[n]!==void 0),...Object.keys(e).filter(n=>e[n]!==void 0),...t.length>0?["body"]:[]])].sort((n,r)=>n.localeCompare(r))}function dC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Vc(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),a=x(o,O()),i=await q(r,e,o.id_prefix,o.item_format,a.type_to_folder);if(!i)throw await _t(r,e,o.id_prefix,a.type_to_folder);let s=await se(i,{schema:o.schema}),c=s.document.metadata,m=k(),p=C(t.author,o.author_default),u=await gr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:a.type_to_folder,probeExisting:!1}),f=$(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:u,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=Tt(O()),g=nt({metadata:h,body:s.document.body},{schema:o.schema,extensionFieldNames:y}),w=await qn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),b=lC(g.metadata,g.body),S=dt(r,g.metadata.type,u,o.item_format,a.type_to_folder),T=et(r,u),L=await Te(r,u,o.locks.ttl_seconds,p,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),P={metadata:{},body:""},M,z;try{let H=await $t(r,p,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await qn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let J=await q(r,u,o.id_prefix,o.item_format,a.type_to_folder);if(J)throw new l(`Cannot copy to ${u}: an item with that id already exists at ${J.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${u} already exists at ${J.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await ne(S,Be(g,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let Z=Le({nowIso:m,author:p,op:"create",before:P,after:g,message:dC(i.id,t.message)});await xt(T,Z)}catch(Z){throw await En(S),Z}z=await Ft({pmRoot:r,preferredFormat:o.item_format,typeToFolder:a.type_to_folder,schema:o.schema,itemPath:S,document:g})}finally{await H()}M=[...await Y({path:S,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:P,after:g,changed_fields:b}),...await Y({path:T,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:P,after:g,changed_fields:b})],In({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Qt(g.metadata,b),changed_fields:b})}finally{await L()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:b,warnings:[...xa(w),...z,...M],...w===void 0?{}:{similarity_advisory:w}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c8f85c4-33c4-5e7d-b01d-b95c8281250d")}catch{}})();var mC="hierarchy-integrity";async function Ja(e){let t=e.required?await Te(e.pmRoot,mC,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Xa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Qa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Za(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(io.includes(t))return t;let n=ue(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function ei(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c22dc1f8-285a-5858-9087-17a8deed6db8")}catch{}})();var pC=new Set(["none","null"]);function ti(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function We(e){return e===void 0?!1:pC.has(e.trim().toLowerCase())}function ni(e,t,n){if(!We(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Oe(e,t,n){if(!e||e.length===0||!e.some(o=>We(o)))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ri(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(o.some(a=>We(a))){if(o.filter(a=>!We(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var uC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function gg(e,t,n,r){if(uC.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Ho("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b968be78-8489-5735-8f95-8e38a36e160a")}catch{}})();var vt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],fC=new Set(vt);function yg(e){return da(e,vt)}function oi(e,t){let n={},r=[];for(let[o,a]of Object.entries(e)){let i=o.toLowerCase();if(!fC.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[i]=a}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:o,...a}=n;return{...a,command:a.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dd87416a-25ec-5dfe-8c54-ef7f43529ecc")}catch{}})();var ln=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Er,hf,"FORCE_COLOR"]),si=/^[A-Za-z_][A-Za-z0-9_]*$/,cn=["schema","tracker","auto","none"],wg=["source","isolated","snapshot"];function Mr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let a=o.indexOf("=");if(a<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1);if(!si.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(ln.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=s}return Object.keys(r).length>0?r:void 0}function Dr(e,t){if(!e)return;let n=Un(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!si.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(ln.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function ci(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function li(e,t){if(!e)return;let n=e.trim().toLowerCase();if(cn.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${cn.join(", ")}`,d.USAGE)}function dn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(wg.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${wg.join(", ")}`,d.USAGE)}function mn(e){if(!e)return;let t=Un(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Vn(e,t,n){let r=mn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(a){throw new l(`${t} ${n} includes invalid regex "${o}": ${a instanceof Error?a.message:String(a)}`,d.USAGE)}return r}}function di(e,t){if(!e)return;let n=ue(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function mi(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let a=o.indexOf("=");if(a<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1).trim();if(i.length===0||s.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[i]=s}return Object.keys(r).length>0?r:void 0}function pi(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let a=o.indexOf("=");if(a<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1).trim();if(i.length===0||s.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(s);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,d.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var _C=new Set(vt);function ui(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hC(e,t){let n={},r=[];for(let[o,a]of Object.entries(e)){let i=o.toLowerCase();if(!_C.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=a}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`);return n}function sn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function ai(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let a=o.filter(i=>i.length>0);return a.length>0?a:void 0}function vg(e,t,n){let r=ai(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(a){throw n(`field "${t}" includes invalid regex "${o}": ${a instanceof Error?a.message:String(a)}`)}return r}}function ii(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function gC(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:ii(n,"timeout_seconds",t),a=r===void 0?void 0:ii(r,"timeout",t);if(o!==void 0&&a!==void 0&&o!==a)throw t("timeout and timeout_seconds must match when both are provided");let i=o??a;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function yC(e,t){let n=sn(e,"scope",t);if(n===void 0)return"project";if(!ct.includes(n))throw t(`field "scope" must be one of: ${ct.join(", ")}`);return n}function wC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ui(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,a]of Object.entries(n)){if(typeof a!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!si.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(ln.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=a}return Object.keys(r).length>0?r:void 0}function vC(e,t){let n=ai(e,"env_clear",t);if(n){for(let r of n){if(!si.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(ln.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function bC(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function kC(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=ii(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function SC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ui(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,a]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(a)}return Object.keys(r).length>0?r:void 0}function EC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ui(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,a]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=ii(a,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function AC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!ui(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${vt.join(", ")}.`);let o=hC(e,r),a=sn(o,"command",r),i=sn(o,"cmd",r);if(a!==void 0&&i!==void 0&&a!==i)throw r("command and cmd must match when both are provided");let s=a??i;if(s===void 0||s.trim().length===0)throw r('requires a non-empty "command" string');let c=sn(o,"path",r),m=sn(o,"pm_context_mode",r);if(m!==void 0&&!cn.includes(m))throw r(`field "pm_context_mode" must be one of: ${cn.join(", ")}`);let p=dn(sn(o,"workspace_context_mode",r),`${n} ${t}`),u=sn(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:yC(o,r),timeout_seconds:gC(o,r),pm_context_mode:m,workspace_context_mode:p,env_set:wC(o,r),env_clear:vC(o,r),shared_host_safe:bC(o,"shared_host_safe",r),assert_stdout_contains:ai(o,"assert_stdout_contains",r),assert_stdout_regex:vg(o,"assert_stdout_regex",r),assert_stderr_contains:ai(o,"assert_stderr_contains",r),assert_stderr_regex:vg(o,"assert_stderr_regex",r),assert_stdout_min_lines:kC(o,r),assert_json_field_equals:SC(o,r),assert_json_field_gte:EC(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function bg(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(a){throw new l(`${t} value is not valid JSON: ${a instanceof Error?a.message:String(a)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((a,i)=>AC(a,o.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1ffee31a-c272-5494-a04a-01a17b78dd2d")}catch{}})();var Wc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Yc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],kg=[...Wc,...Yc],fi=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function _i(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(We(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let a=e.resolveDefinition(o);if(!a)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(a.metadataKey),n.add(a.optionKey)}return{metadataKeys:t,optionKeys:n}}function hi(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let a of o){if(a.allow_unset===!1)continue;let i=new Set;if(typeof a.key=="string"&&a.key.length>0&&i.add(a.key.toLowerCase()),typeof a.metadata_key=="string"&&a.metadata_key.length>0&&i.add(a.metadata_key.toLowerCase()),typeof a.cli_flag=="string"&&a.cli_flag.length>0&&(i.add(a.cli_flag.replaceAll("-","_").toLowerCase()),i.add(a.cli_flag.toLowerCase())),Array.isArray(a.cli_aliases))for(let s of a.cli_aliases)typeof s!="string"||s.length===0||(i.add(s.replaceAll("-","_").toLowerCase()),i.add(s.toLowerCase()));if(i.has(r))return{optionKey:a.key,metadataKey:a.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Eg(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Jc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function xe(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var Ag=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function TC(e,t){return t==="defined"?e!==void 0:!!e}function Sg(e,t,n){if(!TC(e,n))return;let r=ue(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function CC(e,t,n){let r=e?ie(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function IC(e){return Array.from(new Set(Jc(e).map(t=>xe(t.toLowerCase(),zd,"event weekday")))).sort((t,n)=>ds(t)-ds(n))}function RC(e){return Array.from(new Set(Jc(e).map(t=>{let n=ue(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function OC(e,t){return Array.from(new Set(Jc(e).map(n=>ie(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Tg(e,t,n,r){let o=e.recur_freq?.trim(),a=e.recur_interval?.trim(),i=e.recur_count?.trim(),s=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),p=e.recur_exdates?.trim();if(![o,a,i,s,c,m,p].some(b=>b!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let u=xe(o.toLowerCase(),Kd,"event recurrence frequency"),f=Sg(a,"recur_interval",r),_=Sg(i,"recur_count",r),h=CC(s,t,n),y=IC(c),g=RC(m),w=OC(p,n);return{freq:u,interval:f,count:_,until:h,by_weekday:y.length>0?y:void 0,by_month_day:g.length>0?g:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2c9f586-3e93-5caf-a5c2-38be30c67171")}catch{}})();function Ur(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Gr(e,t,n=Mt()){for(let r of t??[])try{Wd(e,r.id,r.kind,n)}catch(o){throw new l(An(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Cg(e,t){return(await se(e,{schema:t})).document.metadata.created_at}async function xC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Cg(n,t.schema)}function PC(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function NC(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:a})=>a===null?[]:[[o,a]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await Cg(n.get(o),e.context.schema)])));for(let o of e.holders){let a=await xC(o,e.context);if(a!==void 0)for(let i of t){let s=r.get(i.id),c=Date.parse(a),m=Date.parse(s);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw PC({holder:o,dependency:i,sourceCreatedAt:a,targetCreatedAt:s,registry:e.registry})}}}async function pn(e){let t=e.registry??Mt(),n=(e.dependencies??[]).filter(i=>!Xp(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await q(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),a=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,s)=>i<s?-1:1);if(a.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${a.length===1?"":"s"} not found: ${a.join(", ")}`,d.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:a,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${a.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:a,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${a[0]}" --limit 10`}});return await NC({dependencies:n,missingTargets:a,resolutions:o,holders:e.holders??[],registry:t,context:e}),a.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var LC={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function $C(e){return LC[e]}function Xc(e){return $C(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Ig="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",FC="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",MC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,DC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Og=1e3,Qc=60*Og,UC=60*Qc;function Rg(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function GC(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new l(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,d.USAGE);let o=r.replace(/^([+-]?\d+)mo$/i,"$1m"),a=MC.exec(r);if(a){let c=a[1]==="-"?-1:1,m=Number.parseInt(a[2],10)*c;return Rg(n.getTime()+m*Qc,r)}let i=DC.exec(r);if(i){let[,c,m,p,u]=i;if(m||p||u){let f=c==="-"?-1:1,_=Number.parseInt(m??"0",10),h=Number.parseInt(p??"0",10),y=Number.parseInt(u??"0",10),g=_*UC+h*Qc+y*Og;return Rg(n.getTime()+f*g,r)}}let s=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return ie(s,n,"event.duration")}function xg(e,t,n,r){if(t&&n)throw new l(FC,d.USAGE);if(n){let a=GC(e,n);if(a<e)throw new l(Ig,d.USAGE);return a===e?void 0:a}if(!t)return;let o=ie(t,r,"event.end");if(o<e)throw new l(Ig,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var jC=["at","date","text","title"],qC=["start","date","end","duration","title","description","location","timezone","all_day",...Ag],KC=["key","value"];function Pg(e,t){return t==="trimmed"?e?.trim():e}function zC(e,t){return t==="defined"?e!==void 0:!!e}function gi(e,t,n){return e.map(r=>{let o=de(r,"--reminder");Ve(o,"--reminder",jC);let a=Pg(o.at??o.date,n.valueMode),i=Pg(o.text??o.title,n.valueMode);if(!a||!i)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let s=i.trim();if(!s)throw new l("--reminder text must not be empty",d.USAGE);return{at:ie(a,t,"reminder.at"),text:s}})}function yi(e,t,n){return e.map(r=>{let o=de(r,"--event");Ve(o,"--event",qC);let a=(o.start??o.date)?.trim();if(!a)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=ie(a,t,"event.start"),s=o.end?.trim(),c=o.duration?.trim(),m=xg(i,s,c,t),p=o.title,u=o.description,f=o.location,_=o.timezone,h=p?.trim(),y=u?.trim(),g=f?.trim(),w=_?.trim(),b=[["title",p,h],["description",u,y],["location",f,g],["timezone",_,w]];for(let[P,M,z]of b)if(M!==void 0&&!z)throw new l(`--event ${P} must not be empty`,d.USAGE);let S=o.all_day?.trim(),T=Tg(o,i,t,n.recurrenceEmptyNumericGuard),L=zC(S,n.allDayEmptyGuard)?Eg(S,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:L,timezone:w,recurrence:T}})}function wi(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let o,a;if(r.includes(",")||r.includes(`
20
- `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let i=de(r,"--type-option");Ve(i,"--type-option",KC),o=i.key?.trim(),a=i.value?.trim()}else{let i=r.indexOf("="),s=r.indexOf(":"),c=i;if(i<=0&&s>0&&(c=s),c<=0||c===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,c).trim(),a=r.slice(c+1).trim()}if(!o||!a)throw new l("--type-option requires key and value",d.USAGE);t[o]=a}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b72dfe53-b429-5722-aaf3-bc6bbf099d3e")}catch{}})();var HC=["strict","progressive"],BC=["lightweight"],Fg=new Set(["Reminder","Meeting","Event"]),VC=new Set(["author","created_at","text"]),el=[...kg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...fi],WC=(()=>{let e=new Map;for(let t of el)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),vi=new Map(el.map(e=>[e.optionKey,e.canonical])),YC=el.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function JC(e,t){let n=te(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function XC(e,t){let n=e.default_status;if(n!==void 0){let r=te(n,t);if(r)return r}return t.open_status}function Zc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var QC=ti();function Mg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let a=t.unset?[...t.unset]:[];a.includes(o)||a.push(o),t.unset=a};We(t.template)&&(t.template=void 0);let r=new Set([...vi.keys(),"rank"]);for(let o of r){let a=t[o];if(typeof a!="string"||!We(a))continue;let i=o==="rank"?"order":vi.get(o)??o;n(i),t[o]=void 0}return Ie(e,ri(t,QC))}function we(e){if(e!==void 0)return e}function ZC(e,t){return _i({raw:e,supportedFields:YC,resolveDefinition:n=>WC.get(n)??hi(n,"create",t)})}var Ng=["id","kind","type","author","created_at","source_kind"],bi=["path","scope","note"];function e0(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let a=o.trim(),i=ki(a,Ng);Ur(a,i);let s=i?de(o,"--dep"):{id:a,kind:"related"};i&&Ve(s,"--dep",Ng);let c=we(s.id),m=t0(we(s.kind??s.type));if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(c.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(we(s.source_kind)),u=we(s.author);return{id:kr(c,n,p),kind:xe(m,Vt,"dependency kind","kind"),created_at:Zc(s.created_at,t),author:u??r,source_kind:p??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function t0(e){return typeof e=="string"?mo(e)??e.trim():e}function ki(e,t){return da(e,t)?!0:ua(e)}function fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Oe(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let a=o.trim(),i=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},s;try{s=de(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return i();throw m}if(Object.keys(s).filter(m=>!VC.has(m)).length>0)return{created_at:Zc(s.created_at,n),author:we(s.author)??r,text:a};let c=s.text??"";if(c==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Zc(s.created_at,n),author:we(s.author)??r,text:c}}),explicitEmpty:!1})}function tl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=ki(n,bi);Ws(n,"--file","file path",r);let o=r?de(t,"--file"):{path:n};if(r&&Ve(o,"--file",bi),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:xe(o.scope??"project",ct,"file scope"),note:we(o.note)}}),explicitEmpty:!1})}function nl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=ki(n,vt);Ws(n,"--test","test command",r);let o=r?oi(de(t,"--test"),"--test"):{command:n},a=we(o.command),i=we(o.path);if(!a)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let s=we(o.timeout_seconds),c=we(o.timeout);if(s&&c&&s!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=s??c;return{command:a,path:i,scope:xe(o.scope??"project",ct,"test scope"),timeout_seconds:m?ue(m,"timeout_seconds"):void 0,pm_context_mode:li(o.pm_context_mode,"--test"),workspace_context_mode:dn(o.workspace_context_mode,"--test"),env_set:Mr(o.env_set,"--test"),env_clear:Dr(o.env_clear,"--test"),shared_host_safe:ci(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:mn(o.assert_stdout_contains),assert_stdout_regex:Vn(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:mn(o.assert_stderr_contains),assert_stderr_regex:Vn(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:di(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:mi(o.assert_json_field_equals,"--test"),assert_json_field_gte:pi(o.assert_json_field_gte,"--test"),note:we(o.note)}}),explicitEmpty:!1})}function rl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=ki(n,bi),o=r?de(t,"--doc"):{path:n};if(r&&Ve(o,"--doc",bi),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:xe(o.scope??"project",ct,"doc scope"),note:we(o.note)}}),explicitEmpty:!1})}function n0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:gi(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function r0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--event","Use --clear-events to clear linked events."),{values:yi(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function o0(e,t,n,r=[]){let o=[...so.filter(a=>e[a]!==void 0),...r.filter(a=>e[a]!==void 0),...t.length>0?["body"]:[],...n.map(a=>`unset:${a}`)];return Array.from(new Set(o))}function a0(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Lg(e,t,n){let r=rr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function i0(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Dg(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function s0(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Lg(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Lg(r,e.name,"required_create_repeatables"));return n}function c0(e,t,n,r){for(let o of e)if(!(!Dg(t,o)&&!n.has(o)))throw new l(`Option ${Ae("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function l0(e,t,n){if(t!=="strict")return;let r=e.filter(a=>n.has(a)&&!Xc(a));if(r.length===0)return;let o=[...new Set(r.map(a=>Ae("create",a)))].sort((a,i)=>a.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function d0(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:wi(e),explicitEmpty:!1})}async function m0(e){return await fa(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function p0(e){return ft(e)?await m0(e):e}function u0(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${HC.join(", ")}`,d.USAGE)}function f0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${BC.join(", ")}`,d.USAGE)}function _0(e,t,n){let r=u0(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function h0(e,t,n,r){let o=e.name,a=i0(t),i=s0(e,n),s=Tn(e,"create",i);if(s.errors.length>0)throw new l(s.errors.join("; "),d.CONFLICT);c0(s.disabled,a,r,o),l0(s.required,n,r);let c=p=>p==="status"&&e.default_status!==void 0||r.has(p)&&Xc(p)?!0:Dg(a,p),m=s.required.filter(p=>!c(p));return[...new Set(m.map(p=>Ae("create",p)))].sort((p,u)=>p.localeCompare(u))}var Ug=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function g0(e,t){let n=[];for(let r of e){let o=r.match(Ug);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function y0(e,t){return e.filter(n=>{let r=n.match(Ug);return!r||r[2]!==t})}function w0(e,t,n,r){let o=y0(e,t);if(o.length===0)return;let a=Gg(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[a],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function v0(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function b0(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function Gg(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],a=["--status","--priority","--message"],i=[...new Set([...a,...t])],s=new Set(["--title","--description","--type"]);for(let c of i)s.has(c)||(o.push(...b0(c,e.name,r)),s.add(c));for(let c of n){let m=v0(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function ol(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function k0(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function S0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function E0(){let e=O();return e?e.commands.some(t=>t.action==="templates-show"||S0(t.command)==="templates show"):!1}function A0(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[o,a]of Object.entries(n)){if(typeof a=="string"||typeof a=="number"||typeof a=="boolean"){r[o]=a;continue}if(Array.isArray(a)&&a.every(i=>typeof i=="string")){r[o]=[...a];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function T0(e,t,n){if(!E0())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Yo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return A0(r.result,e)}function V(e,t,n){return e.has(t)||n===void 0?void 0:we(n)}function un(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var C0=new Set(["milestone","meeting","reminder","event"]);function jg(e,t,n,r){let o=t!==void 0,a=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return C0.has(e.toLowerCase())&&!o&&!a&&!i}function I0(e,t,n,r,o){let a=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&a.push(`event_without_schedule:${t}:no_time_set`),jg(e,n,r,o)&&a.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),a}async function R0(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await na(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function O0(e,t,n,r,o,a){let i=Ea(ya(o),t.id_prefix);if(Qo(i))return{parent:i,warnings:[]};if(va(r,i,t.id_prefix),await q(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let s=Ke(i,t.id_prefix);return{parent:i,warnings:wa(s,a).warnings}}async function x0(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await O0(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function P0(e){if(e.explicitId===void 0)return gr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||Hu(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=Ke(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function $g(e,t,n,r,o){let a=V(e,t,n);if(a===void 0)return{value:void 0,warnings:[]};let i=ba(r,a,o);return{value:i.value,warnings:i.warnings}}async function N0(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:a,status:i,statusExplicit:s,nowValue:c,author:m}=e,p=e.dependencyValues;if(a===void 0)return{dependencyValues:p,status:i};let u=Ke(a,n.id_prefix),f=await q(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:p,status:i};if((p??[]).some(h=>h.id===f.id&&h.kind==="blocked_by")||(p=[...p??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),s)return{dependencyValues:p,status:i};let _=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((h,y)=>h.localeCompare(y))[0]??o.open_status;return{dependencyValues:p,status:_}}function L0(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&be(r,n)){e.type=r;return}be("Task",n)&&(e.type="Task")}function $0(e,t){return e.options.filter(n=>rr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function F0(e,t,n,r,o){let a=e,i=[];if(a.template!==void 0){let h=a.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await T0(h,t,n);a=Mg(k0(y,a))}if(a.type===void 0&&L0(a,r,o),a.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let s=be(a.type,o);if(!s){let h=Vu(a.type),y=h?be(h,o):void 0;if(y)i.push(`type_coercion:${a.type.trim()}:${y}`),a.type=y,s=y;else throw new l(Rt(a.type,o.types,Ot(n,r.schema)),d.USAGE)}let c=po(s,o);if(!c)throw new l(`Invalid type value "${a.type}"`,d.USAGE);let m=c.name,p=$0(c,a),u=p.map(h=>`${h.key}=${String(a[h.key])}`);if(u.length>0){a.typeOption=[...u,...a.typeOption??[]];for(let h of p)delete a[h.key]}let f=f0(a.schedulePreset);if(f!==void 0&&!Fg.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=_0(a.createMode,f,r.governance.create_mode_default);return{resolvedOptions:a,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function M0(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let a of o)if(a.enabled){if(a.values&&a.values.length>0)throw new l(`Cannot combine ${a.clearFlag} with ${a.valueFlag}`,d.USAGE);n.add(a.metadataKey),r.add(a.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function D0(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let a=vi.get(r)??r;throw new l(`Cannot combine --unset ${a} with ${Ae("create",r)}`,d.USAGE)}}function U0(e){let t=(n,r)=>{let o=vi.get(r),a=o?`Use --unset ${o} to clear this field.`:void 0;ni(n,Ae("create",r),a)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function G0(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}var j0={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function q0(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:a,type:i,createMode:s,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let y=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${y}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),p=[Gg(n,r,o,a),...m.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+i+").")];s==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Fg.has(i)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&u.push(`Required custom field formats: ${m.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let y=h.split(" ",1)[0],g=j0[y];return g?[g]:[]}))];f.length>0&&u.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${i} ${h} ...`),p],nextSteps:u,recovery:s==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function K0(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Pt(t.tags):[];return Ln(n,t.addTags)}function z0(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=un(e,"order",n,o=>ue(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function H0(e,t,n,r,o,a){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?a:ie(r.completedAt,new Date(a),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let s=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:Kc(s,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function B0(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:a,author:i,extensionFieldNames:s,afterDocument:c,beforeDocument:m,historyMessage:p,changedFields:u,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=dt(t,n,r,o.item_format,a.type_to_folder),g=et(t,r),w=Mt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(P=>w.resolve(P.kind)?.hierarchy),S=await Ja({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,L=[];try{let P=await Te(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let M=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await fe(t,o.item_format,a.type_to_folder,void 0,o.schema):void 0;if(await q(t,r,o.id_prefix,o.item_format,a.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if(M){let Z=$(o.schema);Aa(M,[...M,c.metadata],r,Ee=>oe(Ee,Z),w)}let z=await wr({pmRoot:t,settings:o,operation:"create",author:i,before:null,after:c});await Wo({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:ka({pmRoot:t,settings:o,typeToFolder:a.type_to_folder})});let H=await $t(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),J=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await qn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await ne(y,Be(c,{format:o.item_format,schema:o.schema,extensionFieldNames:s}));try{let Z=Le({nowIso:f,author:i,op:"create",before:m,after:c,message:p,context:z.decisions.length===0?void 0:{workflow_policies:z.decisions}});await xt(g,Z)}catch(Z){throw await En(y),Z}T&&(await S(),T=!1),J=await Ft({pmRoot:t,preferredFormat:o.item_format,typeToFolder:a.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await H()}L=[...z.warnings,...M?Ua(M,[...M,c.metadata],r):[],...J,...await Y({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u}),...await Y({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u})],In({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Qt(c.metadata,u),changed_fields:u})}finally{await P()}}finally{T&&await S()}return L}async function Gt(e,t){let n=Mg(await p0(e)),r=E(process.cwd(),t.path);await I(r);let o=await A(r),a=$(o.schema),i=tt(o.schema),s=x(o,O()),c=await F0(n,t,r,o,s);n=c.resolvedOptions;let{typeDefinition:m,type:p,createMode:u}=c,f=ZC(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=M0(n,f);D0(n,f),U0(n);let y=h0(m,n,u,h),g=k(),w=C(we(n.author),o.author_default),b=e0(n.dep,g,o.id_prefix,w),S=fn("--comment",n.comment,g,w),T=fn("--note",n.note,g,w),L=fn("--learning",n.learning,g,w),P=tl(n.file),M=nl(n.test);M.values=await zn(M.values,w,g);let z=rl(n.doc),H=n0(n.reminder,g),J=r0(n.event,g),Z=d0(n.typeOption),Ee=or(p,Z.values,s),Xe=O(),G=Tt(Xe),pe=co(n.field,Xe),Qe=hu(n,i,p),Zi=new Set(Qe.missing_required_flags),es=i.definitions.filter(W=>Zi.has(`--${W.cli_flag}`));G0(pe,Qe,f);let nr=g0(Ee.errors,p),zt=nr.map(W=>`--type-option ${W}=<value>`),Zr=[...new Set([...y,...zt,...Qe.missing_required_flags])].sort((W,cs)=>W.localeCompare(cs));q0({combinedMissingFlags:Zr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:nr,openStatus:a.open_status,type:p,createMode:u,missingRequiredRuntimeFields:es}),w0(Ee.errors,p,m,a);let je=await P0({pmRoot:r,settings:o,typeRegistry:s,explicitId:n.id}),St=n.status!==void 0?JC(n.status,a):XC(m,a),eo=n.priority!==void 0?Fn(n.priority):2,R=f.metadataKeys,Ht=K0(R,n),bn=un(R,"deadline",n.deadline,W=>ie(W,new Date(g),"deadline")),Et=un(R,"estimated_minutes",n.estimatedMinutes,W=>$n(W,"estimated-minutes")),ts=V(R,"acceptance_criteria",n.acceptanceCriteria),Ze=V(R,"definition_of_ready",n.definitionOfReady),ns=z0(R,n),to=V(R,"goal",n.goal),mb=V(R,"objective",n.objective),pb=V(R,"value",n.value),ub=V(R,"impact",n.impact),fb=V(R,"outcome",n.outcome),_b=V(R,"why_now",n.whyNow),hb=V(R,"assignee",n.assignee),gb=R.has("author")?void 0:we(n.author)??w,yb=V(R,"parent",n.parent),Td=await R0(yb,n,R,r),rs=Td.parent,wb=Td.parentSource,vb=V(R,"reviewer",n.reviewer),bb=un(R,"risk",n.risk,W=>xe(Xa(W),kn,"risk")),kb=un(R,"confidence",n.confidence,W=>Za(W)),Sb=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Cd=o.validation.sprint_release_format,Bt=[...c.warnings,...I0(p,je,bn,H.values,J.values)],Id=await x0({itemId:je,parent:rs,pmRoot:r,settings:o,typeRegistry:s,policy:Sb});rs=Id.parent,Bt.push(...Id.warnings);let Rd=$g(R,"sprint",n.sprint,"sprint",Cd),Eb=Rd.value;Bt.push(...Rd.warnings);let Od=$g(R,"release",n.release,"release",Cd),Ab=Od.value;Bt.push(...Od.warnings);let xd=V(R,"blocked_by",n.blockedBy),Pd=await N0({pmRoot:r,settings:o,typeRegistry:s,statusRegistry:a,blockedBy:xd,dependencyValues:b.values,status:St,statusExplicit:n.status!==void 0,nowValue:g,author:w}),os=Pd.dependencyValues;Gr(je,os),Bt.push(...await pn({pmRoot:r,dependencies:os,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:s.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:je,createdAt:g}],schema:o.schema})),St=Pd.status;let Tb=V(R,"blocked_reason",n.blockedReason),Cb=V(R,"unblock_note",n.unblockNote),Ib=V(R,"reporter",n.reporter),Rb=un(R,"severity",n.severity,W=>xe(Qa(W),Sn,"severity")),Ob=V(R,"environment",n.environment),xb=V(R,"repro_steps",n.reproSteps),Nd=V(R,"resolution",n.resolution),Pb=V(R,"expected_result",n.expectedResult),Nb=V(R,"actual_result",n.actualResult),Lb=V(R,"affected_version",n.affectedVersion),$b=V(R,"fixed_version",n.fixedVersion),Fb=V(R,"component",n.component),Mb=un(R,"regression",n.regression,W=>ei(W)),Db=V(R,"customer_impact",n.customerImpact),as=ol(n.title,"--title"),is=n.description??"",no=n.body??"",Ld=await qn({title:as,description:is,body:no},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Bt.push(...xa(Ld));let ss=H0(St,a,o,n,Nd,g),Ub=ss.closeReason,Gb=St===a.close_status?g:void 0,jb=ss.completedAt;Bt.push(...ss.warnings);let ro=js({id:je,title:as,description:is,type:p,type_options:Ee.normalized,status:St,closed_at:Gb,completed_at:jb,close_reason:Ub,priority:eo,tags:Ht,created_at:g,updated_at:g,deadline:bn,assignee:hb,author:gb,estimated_minutes:Et,acceptance_criteria:ts,definition_of_ready:Ze,order:ns,goal:to,objective:mb,value:pb,impact:ub,outcome:fb,why_now:_b,parent:rs,reviewer:vb,risk:bb,confidence:kb,sprint:Eb,release:Ab,blocked_by:xd,blocked_reason:Tb,unblock_note:Cb,reporter:Ib,severity:Rb,environment:Ob,repro_steps:xb,resolution:Nd,expected_result:Pb,actual_result:Nb,affected_version:Lb,fixed_version:$b,component:Fb,regression:Mb,customer_impact:Db,dependencies:os,comments:S.values,notes:T.values,learnings:L.values,files:P.values,tests:M.values,docs:z.values,reminders:H.values,events:J.values,...pe,...Qe.values});try{lo(ro,Xe)}catch(W){throw new l(W instanceof Error?W.message:"Invalid extension item field values",d.USAGE)}let qb=nt({metadata:ro,body:no},{schema:o.schema,extensionFieldNames:G}),Kb={metadata:{},body:""},$d=[..._].sort((W,cs)=>W.localeCompare(cs)),zb=a0(n.message,$d),Fd=o0(ro,no,$d,[...Object.keys(pe),...Object.keys(Qe.values??{})]),Hb=await B0({pmRoot:r,type:p,id:je,settings:o,typeRegistry:s,author:w,extensionFieldNames:G,afterDocument:qb,beforeDocument:Kb,historyMessage:zb,changedFields:Fd,nowValue:g,similarityCandidate:{title:as,description:is,body:no},allowDuplicate:n.allowDuplicate}),Md=structuredClone(ro);u==="strict"&&_.has("dependencies")&&(Md.dependencies=[]);let Bb=gg(je,p,St,a);return jg(p,bn,H.values,J.values)&&Jp(`[pm] warning: ${p} '${je}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${je} --deadline <ISO>' or 'pm update ${je} --event "start=<ISO>,end=<ISO>"'.`),{item:Md,changed_fields:Fd,warnings:[...Bt,...Hb],...Object.fromEntries([["parent_source",wb],["next_transition",Bb],["similarity_advisory",Ld]].filter(W=>W[1]!==void 0))}}import Si from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d29ab3a3-319f-506f-8289-78d786b95255")}catch{}})();async function al(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),a=C(t.author,o.author_default),i=await ef({pmRoot:r,settings:o,id:e,author:a,message:t.message,force:t.force,dryRun:t.dryRun}),s=i.targetPath?Si.relative(r,i.targetPath).split(Si.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...s?{target_path:s}:{},history_retained:Si.relative(r,et(r,i.item.id)).split(Si.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7047beb-5c3a-5d97-acb9-7ddd15a223ec")}catch{}})();async function V0(e){await I(e)}async function il(e,t,n){let r=E(process.cwd(),n.path);if(await V0(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),u=Pn(C(void 0,p.author_default));return await _u(r),await Ga({pmRoot:r,settings:p,principal:u}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await na(r);if(p===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 u=await W0(r,p);return{action:"show",focused_item:p,title:u,message:`Focused on ${p}${u?` (${u})`:""}. New items default --parent to it.`}}let o=await A(r),a=x(o,O()),i=await q(r,e,o.id_prefix,o.item_format,a.type_to_folder);if(!i)throw await _t(r,e,o.id_prefix,a.type_to_folder);let s=Ke(i.id,o.id_prefix),c=await se(i,{schema:o.schema}),m=qg(c.document.metadata.title);return await fu(r,s),await Ga({pmRoot:r,settings:o,principal:Pn(C(void 0,o.author_default)),itemId:s}),{action:"set",focused_item:s,title:m,message:`Focused on ${s}${m?` (${m})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function W0(e,t){let n=await A(e),r=x(n,O()),o=await q(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let a=await se(o,{schema:n.schema});return qg(a.document.metadata.title)}function qg(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Ei(e){return Ho("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ee587b5-5aa8-5d10-89d7-acc4a5edb53f")}catch{}})();var dl=[...Wc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Yc,...fi],Y0=(()=>{let e=new Map;for(let t of dl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Ai=new Map(dl.map(e=>[e.optionKey,e.canonical])),J0=dl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),X0=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),Q0=ti({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Jg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let a=t.unset?[...t.unset]:[];a.includes(o)||a.push(o),t.unset=a},r=new Set([...Ai.keys(),"rank"]);for(let o of r){let a=t[o];if(typeof a!="string"||!We(a))continue;let i=o==="rank"?"order":Ai.get(o)??o;n(i),t[o]=void 0}return Ie(e,ri(t,Q0))}function Xg(e,t,n=[]){return _i({raw:e,supportedFields:J0,resolveDefinition:r=>{let o=n.find(a=>{let i=a.toLowerCase();return i===r||i.replaceAll("_","-")===r||i.replaceAll("-","_")===r});return Y0.get(r)??hi(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var Kg=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function zg(e){let t=e.disallowedFlags.flatMap(r=>{let o=Kg.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=Kg.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function Z0(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let a=(c,m,p)=>{c&&p.push(m)};if(o){let c=[];if(a(t.title!==void 0,"--title",c),a(t.description!==void 0,"--description",c),a(t.body!==void 0,"--body",c),a(t.status!==void 0,"--status",c),a(t.closeReason!==void 0,"--close-reason",c),a(t.priority!==void 0,"--priority",c),a(t.type!==void 0,"--type",c),a(t.tags!==void 0,"--tags",c),a(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),a(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),a(t.deadline!==void 0,"--deadline",c),a(t.estimatedMinutes!==void 0,"--estimate",c),a(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),a(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),a(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),a(t.definitionOfReady!==void 0,"--definition-of-ready",c),a(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),a(t.goal!==void 0,"--goal",c),a(t.objective!==void 0,"--objective",c),a(t.value!==void 0,"--value",c),a(t.impact!==void 0,"--impact",c),a(t.outcome!==void 0,"--outcome",c),a(t.whyNow!==void 0,"--why-now",c),a(t.assignee!==void 0,"--assignee",c),a(t.parent!==void 0,"--parent",c),a(t.reviewer!==void 0,"--reviewer",c),a(t.risk!==void 0,"--risk",c),a(t.confidence!==void 0,"--confidence",c),a(t.sprint!==void 0,"--sprint",c),a(t.release!==void 0,"--release",c),a(t.blockedBy!==void 0,"--blocked-by",c),a(t.blockedReason!==void 0,"--blocked-reason",c),a(t.unblockNote!==void 0,"--unblock-note",c),a(t.reporter!==void 0,"--reporter",c),a(t.severity!==void 0,"--severity",c),a(t.environment!==void 0,"--environment",c),a(t.reproSteps!==void 0,"--repro-steps",c),a(t.resolution!==void 0,"--resolution",c),a(t.expectedResult!==void 0,"--expected-result",c),a(t.actualResult!==void 0,"--actual-result",c),a(t.affectedVersion!==void 0,"--affected-version",c),a(t.fixedVersion!==void 0,"--fixed-version",c),a(t.component!==void 0,"--component",c),a(t.regression!==void 0,"--regression",c),a(t.customerImpact!==void 0,"--customer-impact",c),a(t.depRemove!==void 0,"--dep-remove",c),a(t.replaceDeps===!0,"--replace-deps",c),a(t.replaceTests===!0,"--replace-tests",c),a(t.replaceFiles===!0,"--replace-files",c),a(t.replaceDocs===!0,"--replace-docs",c),a(t.comment!==void 0,"--comment",c),a(t.note!==void 0,"--note",c),a(t.learning!==void 0,"--learning",c),a(t.file!==void 0,"--file",c),a(t.test!==void 0,"--test",c),a(t.doc!==void 0,"--doc",c),a(t.reminder!==void 0,"--reminder",c),a(t.event!==void 0,"--event",c),a(t.typeOption!==void 0,"--type-option",c),a(t.clearDeps===!0,"--clear-deps",c),a(t.clearComments===!0,"--clear-comments",c),a(t.clearNotes===!0,"--clear-notes",c),a(t.clearLearnings===!0,"--clear-learnings",c),a(t.clearFiles===!0,"--clear-files",c),a(t.clearTests===!0,"--clear-tests",c),a(t.clearDocs===!0,"--clear-docs",c),a(t.clearReminders===!0,"--clear-reminders",c),a(t.clearEvents===!0,"--clear-events",c),a(t.clearTypeOptions===!0,"--clear-type-options",c),a(t.force===!0,"--force",c),a(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw zg({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];a(t.status!==void 0,"--status",i),a(t.closeReason!==void 0,"--close-reason",i),a(t.assignee!==void 0,"--assignee",i),a(t.parent!==void 0,"--parent",i),a(t.blockedBy!==void 0,"--blocked-by",i),a(t.blockedReason!==void 0,"--blocked-reason",i),a(t.unblockNote!==void 0,"--unblock-note",i),a(t.dep!==void 0,"--dep",i),a(t.depRemove!==void 0,"--dep-remove",i),a(t.replaceDeps===!0,"--replace-deps",i),a(t.replaceTests===!0,"--replace-tests",i),a(t.replaceFiles===!0,"--replace-files",i),a(t.replaceDocs===!0,"--replace-docs",i),a(t.note!==void 0,"--note",i),a(t.learning!==void 0,"--learning",i),a(t.test!==void 0,"--test",i),a(t.reminder!==void 0,"--reminder",i),a(t.event!==void 0,"--event",i),a(t.clearDeps===!0,"--clear-deps",i),a(t.clearComments===!0,"--clear-comments",i),a(t.clearNotes===!0,"--clear-notes",i),a(t.clearLearnings===!0,"--clear-learnings",i),a(t.clearFiles===!0,"--clear-files",i),a(t.clearTests===!0,"--clear-tests",i),a(t.clearDocs===!0,"--clear-docs",i),a(t.clearReminders===!0,"--clear-reminders",i),a(t.clearEvents===!0,"--clear-events",i);let s=[...n].filter(c=>X0.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...s),i.length>0)throw zg({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${i.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:i})}function eI(e,t){let n=te(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function tI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Cp({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=te(e.fromStatus,e.statusRegistry)??e.fromStatus,r=te(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Ip(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function nI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Qg(e)}function Qg(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Wn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var rI=["id","kind","type","author","created_at","source_kind"],oI=["id","kind","type","author","created_at","source_kind"];function Zg(e){return e.startsWith("```")||e.includes(`
21
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:ua(e)}function ey(e){return typeof e=="string"?mo(e)??e.trim():e}function Ci(e,t,n,r){return e?(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let a=o.trim(),i=Zg(a);Ur(a,i);let s=i?de(o,"--dep"):{id:a,kind:"related"};i&&Ve(s,"--dep",rI);let c=s.id?.trim(),m=ey((s.kind??s.type)?.trim());if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(c.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(Wn(s.source_kind)),u=Wn(s.author);return{id:kr(c,t,p),kind:xe(m,Vt,"dependency kind","kind"),created_at:nI(s.created_at,n),author:u??r,source_kind:p??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function aI(e,t){return e?(Oe(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);let o=Zg(r);if(Ur(r,o,"--dep-remove"),o){let a=de(r,"--dep-remove");Ve(a,"--dep-remove",oI);let i=a.id?.trim();if(!i)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(i.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${i}"`,d.USAGE);let s=ey(Wn(a.kind??a.type)),c=br(Wn(a.source_kind)),m=Wn(a.author),p=Wn(a.created_at);return{id:kr(i,t,c),kind:s?xe(s,Vt,"dependency kind","kind"):void 0,source_kind:c,author:m,created_at:p?Qg(p):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:Ke(r,t)}})):[]}function Ti(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function iI(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),a=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,a].join("\0")}function sI(e,t,n,r){let o=[...e??[]],a=!1;if(t===void 0){let i=o.filter(s=>s.kind!=="blocked_by");return i.length!==o.length&&(o=i,a=!0),a?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),a=!0),a?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function cI(e,t,n,r,o,a){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let s=await q(n,Ke(i,r),r,o,a);return s?{id:s.id}:{unresolved:i}}function lI(e,t,n,r,o){let a=sI(e.dependencies,t,n,r);a.changed&&(a.dependencies===void 0?delete e.dependencies:e.dependencies=a.dependencies,o.includes("dependencies")||o.push("dependencies"))}function dI(e){return`${e.path}::${e.scope}`}function mI(e){return`${e.path}::${e.scope}`}function pI(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function ty(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Hg(e,t){let n=rr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function uI(e,t,n){let r=new Set,o=(a,i)=>{i&&r.add(a)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let a=Xg(e.unset,t,n);for(let i of a.optionKeys)o(i,!0)}return r}function fI(e,t,n,r,o){let a=po(e,n);if(!a)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=Tn(a,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let s=uI(t,r,o);for(let c of i.disabled)if(s.has(Hg(c,e)))throw new l(`Option ${Ae("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!s.has(Hg(c,e)))throw new l(`Missing required option ${Ae("update",c)} for type "${e}"`,d.USAGE)}var _I=new Set(["order","rank"]),hI=ys.filter(e=>!_I.has(e)),ny=["tags","closeReason",...hI],gI=["title","description","body","status","closeReason","completedAt","priority","type",...ys,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],yI=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ie(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>$n(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],wI=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>xe(Xa(e),kn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Za(e)}],vI=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>xe(Qa(e),Sn,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>ei(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function ll(e,t,n){for(let r of e){let o=t[r.optionKey],a=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!a)){if(a){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${Ae("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function bI(e){return Jg(await fa(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function ml(e){return ft(e)?await bI(e):Jg(e)}function kI(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function sl(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function pl(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);sl({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),sl({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),sl({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function SI(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function EI(e){let t={};for(let n of ny)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function AI(e,t){let n=EI(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let a=Ai.get(r)??r;throw new l(`Cannot combine --unset ${a} with ${Ae("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function TI(e){let t=(n,r)=>{let o=Ai.get(r),a=o?`Use --unset ${o} to clear this field.`:void 0;ni(n,Ae("update",r),a)};for(let n of ny)t(e[n],String(n));t(e.order??e.rank,"order"),Oe(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Oe(e.event,"--event","Use --clear-events to clear linked events.")}function CI(e,t){let n={};for(let r of gI)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function II(e){let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await se(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function RI(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function OI(e){e.before&&Aa(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>oe(t,e.statusRegistry),Mt())}function xI(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function PI(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Ea(ya(e.options.parent),e.settings.id_prefix);if(Qo(t))return{resolvedParentValue:t,warnings:[]};if(va(e.id,t,e.settings.id_prefix),await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=Ke(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:wa(n,e.parentReferencePolicy).warnings}}function NI(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function LI(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await se(t,{schema:e.settings.schema}),r=e.options.type!==void 0?be(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=tI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function $I(e){if(!e.fieldFlags.status||te(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let t=Object.entries(e.fieldFlags).filter(([i,s])=>s&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),n=[],r=[];if(t.length>0){let i=Ie(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),s=await it(e.id,i,e.global);r=s.changed_fields,n.push(...s.warnings)}let o=await wt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),a=[...e.workflowTransitionWarnings,...n,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...r,...o.changed_fields],warnings:a}}function FI(e,t,n,r){return t.title!==void 0&&(e.metadata.title=ol(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),te(e.metadata.status,n)??e.metadata.status}var MI=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function DI(e,t){for(let n of MI)e[n]!==void 0&&(delete e[n],t.push(n))}function UI(e,t,n,r,o){let a=eI(n,t.statusRegistry);if(e.metadata.status=a,o.push("status"),a===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!oe(a,t.statusRegistry)&&oe(r,t.statusRegistry)&&DI(e.metadata,o)}function GI(e,t,n,r){if(t.options.status!==void 0&&UI(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!oe(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=ie(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function jI(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&oe(n,t.statusRegistry)&&!oe(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function qI(e,t,n,r){GI(e,t,n,r),jI(e,t,n,r)}function KI(e,t,n){let r=be(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Fn(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=be(t.options.type,t.typeRegistry);if(!o)throw new l(Rt(t.options.type,t.typeRegistry.types,Ot(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return fI(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),zI(e,t,r,n),r}function zI(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let a=wi(t.options.typeOption??[]),i=or(n,a,t.typeRegistry);if(i.errors.length>0)throw new l(i.errors.join("; "),d.USAGE);e.metadata.type_options=i.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=or(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function HI(e,t){let n=new Set(t.map(o=>Ti(o))),r=new Set;return e.filter(o=>{if(!n.has(Ti(o)))return!0;let a=iI(o);return r.has(a)?!1:(r.add(a),!0)})}function BI(e,t,n){let r=t.filter(o=>!e.some(a=>ty(a,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function VI(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=HI(r,t.dependencyUpdates.additions);let o=new Set(r.map(a=>Ti(a)));for(let a of t.dependencyUpdates.additions){let i=Ti(a);o.has(i)||(r.push(a),o.add(i))}}t.dependencyRemovals.length>0&&(BI(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(a=>ty(o,a)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function WI(e,t,n){cl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),cl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),cl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function cl(e,t,n,r,o,a){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],a.push(t))}function YI(e,t,n){Bg(e,"files",t.options.file,t.fileUpdates.values,dI,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),JI(e,t,n),Bg(e,"docs",t.options.doc,t.docUpdates.values,mI,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Bg(e,t,n,r,o,a,i,s){if(!(n===void 0&&!i.has(t))){if(a)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(p=>o(p)));for(let p of r){let u=o(p);m.has(u)||(c.push(p),m.add(u))}e.metadata[t]=c}s.push(t)}}function JI(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Vg(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Vg([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Vg(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=pI(r);n.has(o)||(t.push(r),n.add(o))}return t}function XI(e,t,n){let r=t.options.addTags,o=t.options.removeTags,a=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||a){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Pt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=pa(Ln(i,r),o),n.changedFields.push("tags")}ll(yI,t.options,n),ZI(e,t,n.changedFields)}function QI(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let a=ma(Nn(e.metadata.acceptance_criteria),r,o);if(a.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${a.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:a.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=a.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function ZI(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=ue(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function eR(e,t,n,r){tR(e,t,n.changedFields),nR(e,t,n.changedFields),ll(wI,t.options,n),Wg(e,t,"sprint",r,n.changedFields),Wg(e,t,"release",r,n.changedFields),rR(e,t,n.changedFields),ll(vI,t.options,n)}function tR(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function nR(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function Wg(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let a=ba(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=a.value,r.push(...a.warnings)}o.push(n)}}function rR(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&lI(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function oR(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=gi(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=yi(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function aR(e,t,n){Yg(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Yg(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,a]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),s=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===o)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${s}`,d.USAGE)}qe(e[o],a)||(e[o]=a,n.push(o))}let r=co(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,a]of Object.entries(r))qe(e[o],a)||(e[o]=a,n.push(o))}function Yg(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function iR(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let a=t[o];return a!==void 0&&(!Array.isArray(a)||!qe(a,n[o]??[]))});if(r!==void 0)throw new l(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,d.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function sR(e,t){iR(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],a=[],i=FI(e,t.options,t.statusRegistry,o),s=e.metadata,c={metadataRecord:s,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};qI(e,t,i,o),KI(e,t,o),VI(e,t,o),WI(e,t,o),YI(e,t,o),XI(e,t,c),QI(e,t,c),eR(e,t,c,a),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Gr(e.metadata.id,e.metadata.dependencies),te(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),oR(e,t,o),aR(s,t,o);try{lo(s,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new l(u instanceof Error?u.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,p=[...new Set(o)].filter(u=>u==="body"?e.body!==r:!qe(n[u],m[u]));return t.options.acceptanceCriteria!==void 0&&p.includes("acceptance_criteria")&&a.push(`acceptance_criteria_replaced:${Nn(n.acceptance_criteria).length}:${Nn(m.acceptance_criteria).length}`),{changedFields:p,warnings:a}}async function ry(e,t,n,r={}){t=await ml(t);let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=$(a.schema),s=tt(a.schema),c=O(),m=Tt(c),p=x(a,c),u=a.governance.workflow_enforcement??"off",f=u==="off"?[]:Tp(a.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][a.validation.parent_reference],h=Xg(t.unset,s,m),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);pl(t),SI({definitions:kI(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),Z0(e,t,g),AI(t,h),TI(t);let w=C(t.author,a.author_default),b=new Date,S=b.toISOString(),T=Ci(t.dep,a.id_prefix,S,w);Gr(e,T.additions);let L=await pn({pmRoot:o,dependencies:T.additions,idPrefix:a.id_prefix,itemFormat:a.item_format,typeToFolder:p.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:a.schema}),P=aI(t.depRemove,a.id_prefix),M=fn("--comment",t.comment,S,w),z=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(R=>({...R,author:w}))}:M,H=fn("--note",t.note,S,w),J=fn("--learning",t.learning,S,w),Z=tl(t.file),Ee=nl(t.test);Ee.values=await zn(Ee.values,w,S);let Xe=rl(t.doc),G=[],pe=await PI({id:e,options:t,unsetTargets:h,pmRoot:o,settings:a,typeRegistry:p,parentReferencePolicy:_}),Qe=await cI(t.blockedBy,g.has("blocked_by"),o,a.id_prefix,a.item_format,p.type_to_folder),Zi=Qe.id,es=[...pe.warnings,...NI(Qe)],nr=oa(t,s,t.runtimeFieldCommands),zt=CI(t,nr);if(!Object.values(zt).some(Boolean))return II({pmRoot:o,id:e,settings:a,typeRegistry:p});G.push(...await LI({options:t,fieldFlags:zt,workflowEnforcement:u,typeWorkflows:f,statusRegistry:i,typeRegistry:p,pmRoot:o,id:e,settings:a}));let Zr=await $I({options:t,fieldFlags:zt,statusRegistry:i,workflowTransitionWarnings:G,global:n,id:e});if(Zr)return Zr;xI(t);let je=Mt(),St=zt.parent&&!g.has("parent")||T.additions.some(R=>je.resolve(R.kind)?.hierarchy),eo=await Ja({pmRoot:o,author:w,ttlSeconds:a.locks.ttl_seconds,waitMs:a.locks.wait_ms,required:St});try{let R=await RI({fieldFlags:zt,clearedMetadataKeys:g,pmRoot:o,settings:a,typeToFolder:p.type_to_folder}),Ht,bn,Et=await Zu({pmRoot:o,settings:a,typeToFolder:p.type_to_folder,id:e,op:cR(t,r),author:w,message:t.message,resolveHistoryContext:()=>bn,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Ze){Ht=lR({document:Ze,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),bn=Ht?{recurrence:Ht}:void 0,R=R?.map(to=>to.id===Ze.metadata.id?structuredClone(Ze.metadata):to);let ns=sR(Ze,{options:t,settings:a,typeRegistry:p,statusRegistry:i,runtimeFieldRegistry:s,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:g,dependencyUpdates:T,dependencyRemovals:P,commentUpdates:z,noteUpdates:H,learningUpdates:J,fileUpdates:Z,testUpdates:Ee,docUpdates:Xe,resolvedParentValue:pe.resolvedParentValue,resolvedBlockedByDependencyId:Zi,runtimeFieldUpdates:nr,nowValue:b,nowIso:S,author:w,pmRoot:o});return OI({before:R,document:Ze,statusRegistry:i}),ns}});await eo();let ts=R?Ua(R,R.map(Ze=>Ze.id===Et.item.id?Et.item:Ze),Et.item.id):[];return{item:Et.item,changed_fields:Et.changedFields,warnings:[...G,...es,...L,...ts,...Et.warnings],...Ht===void 0?{}:{lifecycle_transition:Ht}}}finally{await eo()}}function cR(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function lR(e){if(e.recurrenceReason===void 0)return;let t=te(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!oe(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=te(n,e.statusRegistry)??n,o=e.document.metadata,a=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let s=o[i];return typeof s=="string"?[[i,s]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:a}}async function it(e,t,n){return ry(e,t,n)}async function oy(e,t,n,r){let o=await ry(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90a2e91a-50cf-5ad9-87ef-fa95cabf125d")}catch{}})();async function ul(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.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 a=E(process.cwd(),r.path),i=$((await A(a)).schema),s=i.open_status,c=Ei(i),m=n.status??s,p=te(m,i)??m;if(p!==s&&p!==c)throw new l(`Reopen target status must be ${s} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([s,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${s}`,suggested_retry_args:["item","reopen",e,o,"--status",s]}});let u=await oy(e,{status:p,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:u.item,changed_fields:u.changed_fields,warnings:u.warnings,recurrence:u.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56177893-3ccb-5b3f-aa82-9365c26c5d34")}catch{}})();async function ay(e,t,n){return[...await Promise.resolve().then(()=>Eu(et(e,t),t)).catch(()=>[])].reverse().find(r=>r.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ce03100c-3a4f-5ce4-a216-a3fabcfc655e")}catch{}})();var iy="no_available_next_item";function sy(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function jr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=$(a.schema),s=C(r.author,a.author_default),c=Pn(s),m=null,p=!1,u=[],f=await ce({pmRoot:o,settings:a,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let h=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||h;if(m=h.trim().length>0?h:null,bp(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&y!==c){if(r.ifAvailable===!0)return p=!0,u.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let b=await ay(o,_.metadata.id,h);throw new l(`Item ${_.metadata.id} is already ${b}. Use --force to take over, or --if-available to skip without failing.`,d.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${m}->${s}`)}let g={assignee:s,claim_principal:c},w=["assignee","claim_principal"].filter(b=>_.metadata[b]!==g[b]);return Object.assign(_.metadata,g),{changedFields:w,warnings:u}}});return p||await _c({pmRoot:o,settings:a,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:p&&m!==null?m:s,previous_assignee:m,forced:t,...p?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function cy(e,t,n={},r={}){let o=dR(n.maxAttempts),a=await A(E(process.cwd(),t.path)),i={...n,author:C(n.author,a.author_default)},s=await Rr({...r,callerAuthor:i.author,limit:String(o)},t),c=[s.recommended,...s.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return mR(c.slice(0,o),e,t,i)}function dR(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function mR(e,t,n,r={},o=jr){let a=0;for(let s of e){a+=1;try{let c=await o(s.id,t,n,r),m={...c,recommendation:s,attempts:a,available:!0};if(!c.skipped)return m}catch(c){if(!sy(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:a,warnings:[iy]};let i=a===0;throw new l(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?d.NOT_FOUND:d.CONFLICT,{code:iy,why:i?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[i?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function qr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=C(r.author,a.author_default),s=Pn(i),c=r.ownershipReleaseBypass===!0,m=null,p;try{p=await ce({pmRoot:o,settings:a,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){Lr(_,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await hc({pmRoot:o,principal:s,itemId:p.item.id});let u=$(a.schema),f=Gs(p.item.status,u)===Gs(u.in_progress_status,u);return{item:p.item,released_by:i,changed_fields:p.changedFields,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${p.item.id} remains ${p.item.status} and unclaimed. If work is paused, run pm release ${p.item.id} --pause to move it to ${u.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfa2b84f-fb12-53ec-b205-ad69e694bf12")}catch{}})();async function fl(e,t,n){try{return await n()}catch(r){let o=r instanceof l?r.context:{},a=new l(r instanceof Error?r.message:String(r),r instanceof l?r.exitCode:d.GENERIC_FAILURE,{...o,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${o.why?` ${o.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...o.nextSteps??[]]});throw a.cause=r,a}}async function _l(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start requires an explicit item id and cannot be combined with --next or --if-available",d.USAGE);let r=await A(E(process.cwd(),n.path)),o=Ei($(r.schema)),a=await jr(e,t.force===!0,n,t),i=a.item.id,s=await fl(i,"claim",()=>it(i,Dt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:i,action:"start_task",claim:a,update:s}}async function hl(e,t,n){let r=await A(E(process.cwd(),n.path)),o=$(r.schema).open_status,a=await it(e,Dt(t,{status:o},["assignee","pause"]),n),i=a.item.id,s=await fl(i,"update",()=>qr(i,t.force===!0,n,t));return{id:i,action:"pause_task",update:a,release:s}}async function gl(e,t,n,r){let o=await wt(e,t,n,r),a=o.item.id,i=await fl(a,"close",()=>qr(a,n.force===!0,r,n));return{id:a,action:"close_task",close:o,release:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="140b50c9-b0b3-5446-8ef9-5993bf4d830c")}catch{}})();async function ly(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=e.force===!0||r.force===!0,a={...e.args,...r};if(a.start===!0)return _n(e,"start_task");let i=e.args.next===!0||r.next===!0?await cy(o,e.global,a,a):await jr(Kr(e,r),o,e.global,a);return Se(i,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Kr(e,t){let n=e.id??v(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function yl(e,t){return v(e.args,"reason")??v(e.args,"text")??v(t,"reason")??v(t,"text")}async function dy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return r.releaseAssignment===!0?_n(e,"close_task"):Se(await wt(Kr(e,r),yl(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function _n(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=_e(e.args,e.options),a=Kr(e,o),i=Dt(o,{force:e.force===!0||o.force===!0}),s=t==="start_task"?await _l(a,i,e.global):t==="pause_task"?await hl(a,i,e.global):await gl(a,yl(e,o),i,e.global);return Se(s,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function my(e){if(e.options.pause===!0)return _n(e,"pause_task");let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=await qr(Kr(e,r),e.force===!0,e.global,r);return Se(o,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function py(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await ul(Kr(e,r),yl(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a610a47-2af8-51b7-a8ab-2557eaf611e2")}catch{}})();function Ii(e,t){let n=Zt(["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(r=>r.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(r=>r.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${jp(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1e5721e-92fd-5c2e-989f-d63892ed9d90")}catch{}})();var pR=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],uy=["brief","standard","deep"],hy="plan-step-",El="draft",Sl=["bug-investigation","feature-implementation","refactoring-sprint"],fy={"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 uR(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(fy,t)?fy[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${Sl.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Sl[0]}`]});return n.map(r=>({...r}))}function fR(e,t){return t>0?Math.round(e/t*100):0}function gy(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(t=>t!=null).map(t=>(typeof t=="string"?t:String(t)).trim()).filter(t=>t.length>0)}function ze(e){return Array.isArray(e)?e.flatMap(t=>Un(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Un(e,{unique:!1}):[]}function Pe(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function yy(e,t=El){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ms.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${ms.join(", ")}`,d.USAGE);return r}function Al(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ps.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${ps.join(", ")}`,d.USAGE);return r}function wy(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=fs.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${fs.join(", ")}`,d.USAGE);return r}function _R(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=us.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${us.join(", ")}`,d.USAGE);return n}function hR(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=uy.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${uy.join(", ")}`,d.USAGE);return n}function gR(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 l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var wl=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function yR(e,t){let n=e,r={},o=[];for(let a of t){let i=a.startsWith("plan.")?a.slice(5):a;if(i.length!==0){if(!wl.has(i)){o.push(a);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...wl].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...wl].join(",")}`}});return r}function Tl(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let a=o.indexOf("=");if(a<=0)throw new l(`Invalid ${t} entry "${o}"; expected key=value`,d.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[o.slice(0,a).trim().toLowerCase()]=o.slice(a+1).trim()}return n}function Cl(e){let t=Tl(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.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 Il(e){let t=Tl(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.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 Rl(e){let t=Tl(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.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 wR(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=fR(t.completed,t.total),t}function vR(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${hy}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Yn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),a=e.find(i=>i.order===o);if(a)return a}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function _y(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 bR(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((s,c)=>s.order-c.order)){let s=_y(i);if(s){o.push({from_step:i.id,...s});continue}r.push(i)}return{targets:r,skipped:o}}let a=new Set;for(let i of t){let s=Yn(e,i);if(a.has(s.id))continue;a.add(s.id);let c=_y(s);if(c){o.push({from_step:s.id,...c});continue}r.push(s)}return{targets:r,skipped:o}}function kR(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function SR(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function ER(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 De(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,s)=>i.order-s.order),r=wR(n),o=SR(n),a={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??El,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:ER(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(a.steps=n),t==="deep"&&(a.decisions=e.plan_decisions??[],a.discoveries=e.plan_discoveries??[],a.validation=e.plan_validation??[]),a}function Ue(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&&!Qs(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function vy(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.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 AR(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function by(e,t){let n=x(e.settings,O()),r=await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let o=await se(r,{schema:e.settings.schema});return vy(o.document.metadata),{document:o.document,itemId:r.id}}function TR(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of ze(e.related))t.push(`id=${n},kind=related`);for(let n of ze(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of ze(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function CR(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function IR(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||ze(e.dependsOn).length>0||ze(e.link).length>0}function RR(e){let t=e.stepTitle?.trim()||void 0,n=gy(e.step),r=e.template?.trim()?uR(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function OR(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Sl[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.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 xR(e,t){let n=Al(e.stepStatus,"pending"),r=Ol(e,"depends_on"),o=Pe(e.file).map(Cl),a=Pe(e.test).map(Il),i=Pe(e.doc).map(Rl),s=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:a.length>0?a:void 0,docs:i.length>0?i:void 0,created_at:s,updated_at:s,completed_at:n==="completed"?s:void 0}}function PR(e){let t=RR(e),n=IR(e);if(OR(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[xR(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,a)=>({id:`${hy}${String(a+1).padStart(3,"0")}`,order:a+1,title:o,body:t.templateSteps[a]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function ky(e,t,n=[]){Ie(e,t),n.length>0&&ju(t,n)}async function NR(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=yy(e.mode,El),a=_R(e.harness),i=e.fromSearch?.trim(),s=CR(e),{steps:c,hasPerStepDetailOptions:m}=PR(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let p=e.description?.trim()??e.scope?.trim()??r,u=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:p,type:"Plan",template:void 0,file:Pe(e.file),test:Pe(e.test),doc:Pe(e.doc),field:Pe(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:TR(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")};ky(e,f);let _=await Gt(f,t),h=await ce({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let w=["plan_mode"];g.metadata.plan_mode=o,a&&(g.metadata.plan_harness=a,w.push("plan_harness"));let b=e.scope?.trim();b&&(g.metadata.plan_scope=b,w.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(g.metadata.plan_resume_context=S,w.push("plan_resume_context")),g.metadata.plan_steps=c,w.push("plan_steps"),s&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],s],w.push("plan_validation")),u&&(g.metadata.assignee=u,w.push("assignee")),{changedFields:w}}}),y=De(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ue(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function LR(e,t,n){let r=hR(t.depth),o=gR(t.fields),{document:a,itemId:i}=await by(n,e),s=De(a.metadata,o===null?r:"deep");return{action:"show",plan:o===null?s:yR(s,o),next_actions:Ue(i,s),warnings:[],generated_at:k()}}function $R(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function st(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await ce({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(o){vy(o.metadata);let a=$(e.ctx.settings.schema);if(oe(o.metadata.status,a)||Qs(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.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 i=(o.metadata.plan_steps??[]).slice(),s=new Map(Object.entries(o.metadata).filter(([u])=>u.startsWith("plan_")).map(([u,f])=>[u,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let m=i.slice().sort((u,f)=>u.order-f.order).map((u,f)=>({...u,order:f+1}));o.metadata.plan_steps=m;let p=$R(s,o.metadata);return p.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:p.length>0?p:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function FR(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Al(t.stepStatus,"pending"),a=t.allowMultipleActive===!0,{document:i,resultStep:s,itemId:c}=await st({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(p){let u=p.length+1;Sy(p,void 0,o,a);let f=MR(p,t,{order:u,title:r,status:o});return p.push(f),{changedSteps:[f.id],resultStep:f}}}),m=De(i.metadata,"standard");return{action:"add-step",plan:m,step:s,next_actions:Ue(c,m),warnings:[],generated_at:k()}}function Sy(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(a=>a.id!==t&&a.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function MR(e,t,n){let r=Ol(t,"depends_on"),o=Pe(t.file).map(Cl),a=Pe(t.test).map(Il),i=Pe(t.doc).map(Rl),s=k();return{id:vR(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:a.length>0?a:void 0,docs:i.length>0?i:void 0,created_at:s,updated_at:s,completed_at:n.status==="completed"?s:void 0}}function Ol(e,t){let n=ze(e.dependsOn).map(p=>({id:p,kind:t})),r=ze(e.related).map(p=>({id:p,kind:"related"})),o=ze(e.blocks).map(p=>({id:p,kind:"blocks"})),a=ze(e.blockedBy).map(p=>({id:p,kind:"blocked_by"})),i=ze(e.link),s=wy(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(p=>{let u={id:p,kind:s};return c&&(u.note=c),u});return[...n,...r,...o,...a,...m]}async function vl(e,t,n,r){let{document:o,resultStep:a,itemId:i}=await st({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let p=Yn(c,r.stepRef),u=k(),f=r.finalStatus??Al(t.stepStatus,p.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return Sy(c,p.status==="in_progress"?p.id:void 0,f,_),DR(p,t,f,u),m.metadata.updated_at=u,{changedSteps:[p.id],resultStep:p}}}),s=De(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:s,step:a,next_actions:Ue(i,s),warnings:[],generated_at:k()}}function DR(e,t,n,r){UR(e,t,n),GR(e,t),e.status=n,e.updated_at=r,jR(e,n,r)}function UR(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function GR(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=t.stepOwner.trim()||void 0),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 r=Pe(t.file).map(Cl),o=Pe(t.test).map(Il),a=Pe(t.doc).map(Rl);r.length>0&&(e.files=bl(e.files,r)),o.length>0&&(e.tests=bl(e.tests,o)),a.length>0&&(e.docs=bl(e.docs,a))}function bl(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let a=JSON.stringify(o);r.has(a)||(r.add(a),n.push(o))}return n}function jR(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function qR(e,t,n,r,o){let{document:a,itemId:i,resultStep:s}=await st({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(m){let p=Yn(m,r),u=m.filter(_=>_.id!==p.id),f=Math.max(1,Math.min(o,u.length+1));return u.splice(f-1,0,p),u.forEach((_,h)=>{_.order=h+1,_.updated_at=k()}),m.length=0,m.push(...u),{changedSteps:[p.id],resultStep:p}}}),c=De(a.metadata,"standard");return{action:"reorder-step",plan:c,step:s,next_actions:Ue(i,c),warnings:[],generated_at:k()}}async function KR(e,t,n,r){let{document:o,itemId:a,resultStep:i}=await st({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let m=Yn(c,r),p=c.filter(u=>u.id!==m.id);return p.forEach((u,f)=>{u.order=f+1}),c.length=0,c.push(...p),{changedSteps:[m.id],resultStep:m}}}),s=De(o.metadata,"standard");return{action:"remove-step",plan:s,step:i,next_actions:Ue(a,s),warnings:[],generated_at:k()}}async function zR(e,t,n,r){let o=Ol(t,wy(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let a=t.promoteToItemDep===!0,{document:i,itemId:s,resultStep:c}=await st({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(p,u){let f=Yn(p,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of o){let w=h(g);y.has(w)||(_.push(g),y.add(w))}if(f.linked_items=_,f.updated_at=k(),a){let g=u.metadata.dependencies??[],w=S=>`${S.kind}:${S.id}`,b=new Set(g.map(w));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,L={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};b.has(w(L))||(g.push(L),b.add(w(L)))}u.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=De(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ue(s,m),warnings:[],generated_at:k()}}async function HR(e,t,n,r){let o=ze(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:a,itemId:i,resultStep:s}=await st({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let p=Yn(m,r),u=(p.linked_items??[]).filter(f=>!o.includes(f.id));return p.linked_items=u.length>0?u:void 0,p.updated_at=k(),{changedSteps:[p.id],resultStep:p}}}),c=De(a.metadata,"standard");return{action:"unlink",plan:c,step:s,next_actions:Ue(i,c),warnings:[],generated_at:k()}}async function kl(e,t,n,r){let o=kR(r,t);if(!o){let m=`--${r}-text`,p=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${p} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let a=C(t.author,n.settings.author_default),{document:i,itemId:s}=await st({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,p){let u=k();if(r==="decision"){let _=p.metadata.plan_decisions??[];return _.push({ts:u,author:a,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),p.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=p.metadata.plan_discoveries??[];return _.push({ts:u,author:a,text:o}),p.metadata.plan_discoveries=_,{changedSteps:[]}}let f=p.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),p.metadata.plan_validation=f,{changedSteps:[]}}}),c=De(i.metadata,"deep");return{action:r,plan:c,next_actions:Ue(s,c),warnings:[],generated_at:k()}}async function BR(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:a}=await st({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(s,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=De(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Ue(a,i),warnings:[],generated_at:k()}}async function VR(e,t,n){let r=yy(t.mode??"approved","approved"),{document:o,itemId:a}=await st({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(s,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=De(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Ue(a,i),warnings:[],generated_at:k()}}function Ey(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function WR(e,t){let n=De(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ue(e.itemId,n),warnings:Ey(t),generated_at:k()}}function YR(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let a=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${a}`)}return r}async function JR(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Pe(e.options.field)){let a=o.indexOf("=");if(a<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let c=i.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 l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let[m,...p]=c,u=`${m}${p.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(u))throw new l(`Invalid --field entry "${o}"; "${u}" is reserved by materialize and cannot be overridden`,d.USAGE);n[u]=s}for(let o of e.targets){let a={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:YR(e.parent,e.planItemId,o)};ky(e.options,a,["description",...Object.keys(n)]);let i=await Gt(a,{path:e.pmRoot});t.push({id:i.item.id,title:i.item.title,type:e.resolvedTypeName,parent:i.item.parent,tags:i.item.tags??[],from_step:o.id})}return t}function XR(e,t,n){for(let r of t){let o=n.find(s=>s.from_step===r.id);if(!o)continue;let a=e.find(s=>s.id===r.id);if(!a)continue;let i=a.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),a.linked_items=i,a.updated_at=k()}}async function QR(e,t,n){let r=ze(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",a=x(n.settings,O()),i=be(o,a);if(!i)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let s=t.materializeParent?.trim()||e,c=t.materializeTags,m=await by(n,e),p=(m.document.metadata.plan_steps??[]).slice(),{targets:u,skipped:f}=bR(p,r);if(u.length===0){if(f.length>0)return WR(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await JR({targets:u,parent:s,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await st({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return XR(w,u,_),{changedSteps:u.map(b=>b.id)}}}),g=De(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ue(y,g),warnings:Ey(f),generated_at:k()}}function ZR(e){if(e.subcommand==="create")return e;let t=gy(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:Ie(e.options,{...e.options,stepTitle:t[0]})}:e}function bt(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function hn(e,t){let n=bt(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function eO(e){let t=hn(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var tO={create:(e,t)=>NR(e.options,e.global,t),show:(e,t)=>LR(bt(e,"show"),e.options,t),"add-step":(e,t)=>FR(bt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=hn(e,"update-step");return vl(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=hn(e,"complete-step");return vl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=hn(e,"block-step");return vl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=eO(e);return qR(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=hn(e,"remove-step");return KR(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=hn(e,"link");return zR(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=hn(e,"unlink");return HR(n.id,e.options,t,n.stepRef)},decision:(e,t)=>kl(bt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>kl(bt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>kl(bt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>BR(bt(e,"resume"),e.options,t),approve:(e,t)=>VR(bt(e,"approve"),e.options,t),materialize:(e,t)=>QR(bt(e,"materialize"),e.options,t)};function nO(e){let t=tO[e];if(!t)throw Ce({command_path:"plan",token:e,allowed:pR});return t}async function Ay(e){let t=await AR(e.global),n=ZR(e),r=await nO(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Ii(r,t.pmRoot)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a59a772-3e2a-5ae2-88c1-a96bc36f9f85")}catch{}})();var Cy=1,Pl="update-many",rO=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),oO=["--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(", "),aO={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"},iO=[{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"}],sO={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},Iy=e=>{let t={};for(let[n,r]of Object.entries(e))rO.has(n)||r!==void 0&&(t[n]=r);return t},cO=e=>Object.keys(Iy(e)).length>0,Ry=e=>typeof e=="string"?e.trim():e,lO=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},xl=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},dO=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Ry(e)},mO={priority:lO,estimatedMinutes:xl,order:xl,rank:xl,regression:dO},pO=(e,t)=>{if(t!==void 0)return(mO[e]??Ry)(t)},uO=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return sO[t]??t},Ri=(e,t)=>qe(e,t),fO=(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,hO=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Ty=(e,t)=>t===void 0?void 0:e[t],Jn=e=>Array.isArray(e)?e.length:0,gO=(e,t,n)=>{let r=n[e.addKey],o=Ty(n,e.removeKey),a=Jn(r),i=Jn(o),s=n[e.clearKey]===!0,c=Ty(n,e.replaceKey)===!0;if(![s,c,a>0,i>0].includes(!0))return;let m=fO(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:hO({replace:c,clear:s,removeCount:i}),clear:s,replace:c,add_count:a,remove_count:i,before_count:_O(e.field,m)}}},yO=(e,t)=>{let n=[];for(let r of iO){let o=gO(r,e,t);o!==void 0&&n.push(o)}return n},wO=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],vO=(e,t)=>{if(![t.tags!==void 0,Jn(t.addTags)>0,Jn(t.removeTags)>0].includes(!0))return;let n=wO(e.tags),r=t.tags===void 0?n:Pt(t.tags),o=Ln(r,t.addTags),a=pa(o,t.removeTags).slice().sort((s,c)=>s.localeCompare(c)),i=n.slice().sort((s,c)=>s.localeCompare(c));if(!Ri(i,a))return{field:"tags",before:n,after:a}},bO=(e,t)=>{let n=e.acceptance_criteria,r=ma(Nn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!Ri(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},kO=(e,t,n)=>{for(let[r,o]of Object.entries(aO)){let a=n[r];if(a===void 0)continue;let i=t[o],s=pO(r,a);Ri(i,s)||e.push({field:o,before:i,after:s})}},SO=(e,t,n,r)=>{let o=oa(n,r,["update_many"]);for(let[a,i]of Object.entries(o)){let s=t[a];Ri(s,i)||e.push({field:a,before:s,after:i})}},EO=(e,t,n)=>{for(let r of n??[]){let o=uO(r),a=t[o];a!==void 0&&e.push({field:o,before:a,after:null})}},AO=(e,t,n={})=>{let r=e,o=[],a=vO(r,n);if(a&&o.push(a),kO(o,r,n),Jn(n.addAc)>0||Jn(n.removeAc)>0){let i=bO(r,n);i!==void 0&&o.push(i)}return o.push(...yO(r,n)),SO(o,r,n,t),EO(o,r,n.unset),{id:e.id,changes:o}},TO=(e,t)=>Bu(e,t,{strict:!0,flagLabel:"--filter-status"}),CO=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},IO=[({update:e})=>{e.priority!==void 0&&Fn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,O());if(!be(e.type,r))throw new l(Rt(e.type,r.types,Ot(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!te(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&ie(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&$n(e.estimatedMinutes,"estimated-minutes")}],RO=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let a of IO)a(o)},OO=async e=>{let t=await ca(e.pmRoot,Pl,e.rollbackId,Cy),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await la(t.items,(o,a)=>an(o,a,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...en({applied:r.restored_ids.length,skipped:0,failed:r.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:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},xO=async e=>{let t={schema_version:Cy,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 sa(e.pmRoot,Pl,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},PO=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Nl=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},NO=async e=>{let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:$(n.schema),runtimeFieldRegistry:tt(n.schema)}},LO=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Ir(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return OO({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},$O=async e=>{TO(e.options.status,e.runtime.statusRegistry);let t=await ht(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(o=>{let a=AO(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?a:{...a,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await ht(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:PO(e.options.list?.ids,r)}},FO=e=>({outcome:"effect",exit_code:d.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:[],...Nl(e)}),MO=e=>({...en({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:[],...Nl(e)}),DO=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(a=>a.changes.length>0).map(a=>a.id));for(let a of e.items){if(!o.has(a.id)){t.push({id:a.id,status:"skipped"});continue}try{let i=Ys({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),s=await it(a.id,i,e.global);t.push({id:a.id,status:"updated",changed_fields:s.changed_fields,warnings:s.warnings}),n.push(a.id)}catch(i){t.push({id:a.id,status:"failed",error:An(i)})}}return{rows:t,updatedIds:n}},UO=async e=>{if(e.plan.actionable.length===0)return MO(e.plan);let t=k(),n=ia(Pl,t),r=new Set(e.plan.actionable.map(u=>u.id)),o=e.plan.listed.items.filter(u=>r.has(u.id)).map(u=>({id:u.id,target_updated_at:u.updated_at})),a=e.options.checkpoint===!1?void 0:await xO({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:o}),i=await DO({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),s=u=>i.rows.filter(f=>f.status===u).length,c=s("updated"),m=s("skipped"),p=s("failed");return{...en({applied:c,skipped:m,failed:p,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,...a?{checkpoint:a}:{},updated_count:c,skipped_count:m,failed_count:p,rows:i.rows,ids:i.updatedIds,...Nl(e.plan)}},Oy=async(e,t)=>{let n=await NO(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Ys(await ml(e.update))});let o=Iy(e.update);if(CO(e.list),r!==void 0)return LO({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!cO(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${oO}), or pass --dry-run for a filter-only preview.`,d.USAGE);RO(e.update,n.settings,n.statusRegistry,n.pmRoot),pl(e.update);let a=await pn({pmRoot:n.pmRoot,dependencies:Ci(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await $O({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:a});return await pn({pmRoot:n.pmRoot,dependencies:Ci(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(s=>({id:s.id,createdAt:s.created_at})),schema:n.settings.schema}),e.dryRun===!0?FO(i):UO({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6263346a-08ee-5eb9-81b9-47e933793c07")}catch{}})();function GO(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function jO(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 qO(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function xy(e,t,n){let r=GO(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let a=r===void 0?void 0:Yt(r),i=[t.since,t.eventType].some(h=>h!==void 0),s=qO(t.since),c=yr(t.limit),m=await Bn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await Wa(a===void 0?t:{add:a},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Hn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:jO(r)},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."]}}),p=t.eventType?.trim(),u=m.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[s===void 0,Date.parse(h.created_at)>=(s??Number.POSITIVE_INFINITY)].includes(!0),w=[!p,h.event_type===p].includes(!0);return[!i,[y,g,w].every(Boolean)].includes(!0)}),f=i?xc(u,c):u,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:u.length,returned_count:f.length,has_more:f.length<u.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}import tx from"node:path";import KO from"node:fs/promises";import Py from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ac2020a4-78bf-5aa3-a5c4-88d3196dfb1f")}catch{}})();var zO="templates",HO=".json",BO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,VO=Zo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),WO=new Set(VO);function YO(e){let t=e.trim();if(!BO.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function Ny(e){return Py.join(e,zO)}function Ly(e,t){return Py.join(Ny(e),`${t}${HO}`)}async function JO(e){await I(e)}function $y(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function XO(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(WO.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(a=>typeof a=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return $y(t)}function QO(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[o,a]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof a=="string"){r[i]=a;continue}if(Array.isArray(a)&&a.every(s=>typeof s=="string")){r[i]=[...a];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return $y(r)}function ZO(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,o=QO(r.options,t),a=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:a,updated_at:typeof r.updated_at=="string"?r.updated_at:a,options:o}}async function ex(e,t){let n=await ee(Ly(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return ZO(n,t)}async function Ll(e,t,n){let r=E(process.cwd(),n.path);await JO(r);let o=YO(e),a=XO(t);if(Object.keys(a).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=k(),s=Ly(r,o),c=i;await j(s)&&(c=(await ex(r,o)).created_at);let m={name:o,created_at:c,updated_at:i,options:a},p=await A(r);return await KO.mkdir(Ny(r),{recursive:!0}),await ot({pmRoot:r,filePath:s,raw:`${JSON.stringify(m,null,2)}
22
- `,op:"templates:save",author:C(void 0,p.author_default),lockTtlSeconds:p.locks.ttl_seconds,lockWaitMs:p.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:s,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa4e2ff3-dc3b-5688-bf40-bdd71c65320b")}catch{}})();var Uy=["list","show","apply","lint"],nx="schema-types",rx="schema-statuses",ox="schema-fields";function Oi(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Gy(){let{profiles:e,warnings:t}=yp(Oi());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:Sp(n.definition)})),warnings:t,generated_at:k()}}function jy(e){let t;try{t=Ko(e,Oi())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...Ep(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function qy(e){let t;try{t=Ko(e,Oi())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=Zp(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function ax(e,t){return tx.join(e,"templates",`${t}.json`)}async function ix(e,t){let n=await ee(ax(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Fy(e,t,n,r){let o=new Map;for(let a of r.templates){let i=await ix(e,a.name);i!==void 0&&o.set(a.name,i)}return{typesRaw:await ee(pt(e,t.files.types,mt.types)),statusesRaw:await ee(pt(e,t.files.statuses,mt.statuses)),fieldsRaw:await ee(pt(e,t.files.fields,mt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Xn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function My(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Xn(t.types.changes),statuses:Xn(t.statuses.changes),fields:Xn(t.fields.changes),workflows:Xn(t.workflows.changes.map(a=>({key:a.type,status:a.status}))),config:Xn(t.config.changes),templates:Xn(t.templates.changes.map(a=>({key:a.name,status:a.status}))),packages:t.packages,warnings:[...new Set(o)].sort((a,i)=>a.localeCompare(i)),generated_at:k()}}async function sx(e){await I(e)}function cx(e){try{let t=Ko(e,Oi());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Ky(e,t,n){let r=E(process.cwd(),n.path);await sx(r);let o=cx(e),a=o.profile,i=o.warnings,s=t.dryRun===!0,c=await A(r),m=zo(c.schema);if(s){let w=await Fy(r,m,c,a),b=Dy(a,w);return My(a,b,!1,!0,[...i])}let p=C(t.author,c.author_default),u=Mu(c),f=!!t.force,_=[...i],h=[],y=async w=>{h.push(await Te(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(nx),await y(rx),await y(ox);let w=await Fy(r,m,c,a);if(g=Dy(a,w),g.types.changed){let b=pt(r,m.files.types,mt.types);await ot({pmRoot:r,filePath:b,raw:qo(g.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(a.types.map(L=>pp(L).name)),T=g.types.file.definitions.filter(L=>S.has(L.name));await Ef(r,T,_,"profile:apply-type-folder"),_.push(...await Y({path:b,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let b=pt(r,m.files.statuses,mt.statuses);await ot({pmRoot:r,filePath:b,raw:kp(g.statuses.file),op:"profile:apply-statuses",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let b=pt(r,m.files.fields,mt.fields);await ot({pmRoot:r,filePath:b,raw:wp(g.fields.file),op:"profile:apply-fields",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let b of g.config.changes){if(b.status==="unchanged")continue;let S=Bo(b.key);S!==void 0&&Vo(c,S,b.value)}c.schema.type_workflows=g.workflows.result,await $e(r,c,"profile:apply-config")}for(let b of g.templates.changes)b.status!=="unchanged"&&await Ll(b.name,{...b.options},n)}finally{for(let w of h.reverse())try{await w()}catch{}}return My(a,g,g.changed,!1,_)}function Dy(e,t){try{return eu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import _x from"node:fs/promises";import Ml from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c34cc860-67c7-548b-99ff-f4155ef44bb0")}catch{}})();var Hy=10,gn="https://schema.unbrained.dev/pm/eval-query-set/v1";var xi={schema:gn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Ye=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},lx=new Set(["keyword","semantic","hybrid"]);function zy(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function dx(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=zy(r,n),a=Array.from({length:t.size},()=>1),i=zy(a,n);return i===0?0:o/i}function mx(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function $l(e,t,n){let r=Math.min(n,e.length),o=0;for(let a=0;a<r;a+=1)t.has(e[a])&&(o+=1);return o}function px(e,t,n){return n<=0?0:$l(e,t,n)/n}function ux(e,t,n){return t.size===0?0:$l(e,t,n)/t.size}function By(e,t,n){return{ndcg:dx(e,t,n),mrr:mx(e,t,n),precision:px(e,t,n),recall:ux(e,t,n),relevant_total:t.size,retrieved_relevant:$l(e,t,n)}}function Vy(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function fx(e,t){if(typeof e!="object"||e===null)throw new Ye(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Ye(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Ye(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(a=>typeof a!="string"))throw new Ye(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(a=>a.trim()).filter(a=>a.length>0))];if(o.length===0)throw new Ye(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!lx.has(n.mode)))throw new Ye(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:M_(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Fl(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==gn)throw new Ye(`Unsupported eval query set schema; expected "${gn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Ye('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Ye("Eval query set must contain at least one query");return{schema:gn,queries:n.map((r,o)=>fx(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();var hx=Ml.join("search","eval-queries.json"),Dl={schema:gn,examples:[JSON.stringify(xi)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},gx=new Set(["keyword","semantic","hybrid"]),yx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!gx.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},wx=e=>{if(e===void 0||e==="")return Hy;let t=Jd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},vx=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},jt=e=>Math.round(e*1e4)/1e4,bx=async e=>{try{return await _x.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Dl,examples:[`echo '${JSON.stringify(xi)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},kx=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Dl)}},Sx=e=>{try{return Fl(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Dl)}},Ex=async e=>Sx(kx(await bx(e),e)),Ax=async(e,t,n,r)=>{let o=e.mode??t,a=(await Or(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),i=By(a,new Set(e.relevant_ids),n);return{metrics:i,report:{query:e.query,...e.minimum===void 0?{}:{violations:D_(i,e.minimum)},mode:o,relevant_total:i.relevant_total,retrieved_relevant:i.retrieved_relevant,ndcg:jt(i.ndcg),mrr:jt(i.mrr),precision:jt(i.precision),recall:jt(i.recall)}}},Tx=(e,t,n,r)=>{let o=Vy(n);return{k:e,query_count:t.length,aggregate:{ndcg:jt(o.ndcg),mrr:jt(o.mrr),precision:jt(o.precision),recall:jt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:(r===void 0||o.ndcg>=r)&&t.every(a=>(a.violations?.length??0)===0)}},Wy=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=wx(e.k),o=yx(e.mode),a=vx(e.failUnder),i=e.queries?Ml.resolve(process.cwd(),e.queries):Ml.join(n,hx),s=await Ex(i),c=[],m=[];for(let p of s.queries){let{report:u,metrics:f}=await Ax(p,o,r,t);m.push(f),c.push(u)}return Tx(r,c,m,a)};import{readFile as Cx,writeFile as Ix}from"node:fs/promises";import Rx from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abbd522e-582e-584b-bf25-e065173918f4")}catch{}})();var Yy=["item","history","relationship","json"];function Ox(e){let t=e.trim().toLowerCase();if(Yy.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${Yy.join(", ")}.`,d.USAGE)}function xx(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function Ul(e,t){try{return await Cx(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function Px(e){let t=E(process.cwd(),e.path);return await j(re(t))?A(t):null}function Nx(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Jy(e,t){let n=Ox(e.artifact),r=xx(e.prefer),o=Rx.resolve(e.outputPath??e.oursPath),[a,i,s]=await Promise.all([Ul(e.basePath,"base"),Ul(e.oursPath,"ours"),Ul(e.theirsPath,"theirs")]),c,m,p=[],u={};if(n==="history"){let _=t_(a,i,s);c=_.merged,u.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=n_(a,i,s);c=_.merged,u.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await Px(t),h=Nx(e.itemPath??o,_),y=Tt(O()),g=r_(a,i,s,{format:h,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=g.merged,p.push(...g.conflict_fields),u.item={fields_from_theirs:g.fields_from_theirs,union_fields:g.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let w=ku(c,{format:h,schema:_?.schema,extensionFieldNames:y}),b=w.metadata,S=[...new Set([...g.fields_from_theirs,...g.union_fields,...g.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:g.fields_from_theirs,unionFields:g.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,e_(T==="body"?w.body:b[T])])),decisions:g.conflict_decisions,operation:await a_(process.cwd(),e.itemPath)}}}else{let _=o_(a,i,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await Ix(o,c,"utf8"),m!==void 0){let _=await s_(m);_!==null&&(u.receipt=nn(_))}let f=[];if(p.length>0){let _=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${p.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. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.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:p.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:p,...u,guidance:f,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="450eabe6-334a-587c-b838-5ca42519296f")}catch{}})();async function Xy(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await i_(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Ut(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Ut(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??"Settle rebase receipt after exact original Git state restoration",auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...nn(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Na(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as Lx}from"node:fs/promises";import $x from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b07f6f1-2c84-583c-afb2-80f219d19863")}catch{}})();var Fx=4;function Qy(e){let t=e.checks.find(s=>s.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,a=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,i=Array.isArray(o)?o.flatMap(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return[];let c=s;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:r,truncated:a,coordinates:i}}async function Mx(e,t){let n=[];for(let r of t){let o;try{o=await Lx($x.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let a=o.split(/\r?\n/)[r.history_line-1];if(a===void 0||a.trim().length===0)continue;let i;try{i=JSON.parse(a)}catch{continue}let s=p_(i,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!m_(s)||s.eventTimestamp===void 0||Xo(s.eventTimestamp,d_)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function Dx(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 r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Ut(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:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function Ux(e){try{return{status:"fulfilled",value:await Ut(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 Gx(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,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[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function jx(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Na(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}async function Zy(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),a=Qy(o),i=await Mx(r,a.coordinates),s=await Ta(r),c=s??r,m=await c_(c,{includeLossless:!0,pmRoot:r});if(m.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${m.invalid_evidence_count} invalid receipt evidence file(s).`,d.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"}});let p=await Dx({candidates:i,options:e,global:t}),u=m.receipts,f=await Xy({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),_=new Set(f),h=new Map;for(let G of u.filter(pe=>!_.has(pe.id))){let pe=h.get(G.item_id)??[];pe.push(G),h.set(G.item_id,pe)}let y=Object.fromEntries([...h].map(([G,pe])=>[G,{merge:{receipts:pe.map(nn)}}])),g=Object.fromEntries([...h].map(([G,pe])=>[G,{gitWorkspaceRoot:s,receipts:pe}])),w=await $a({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:y,...u.length>0?{mergeReceiptProofById:g}:{}},t),b=new Set(w.streams.map(G=>G.id)),S=[...h.keys()].filter(G=>!b.has(G)),T=await Ff(S,Fx,G=>Ux({id:G,dryRun:n,options:e,global:t,auditContext:y[G],mergeReceiptProof:g[G]}));Gx({receiptOnlyIds:S,results:T,repair:w});let L=await jx({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),P=await Da({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),M=p===0?o:await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),z=Qy(M),H=P.checks.every(G=>G.status==="ok"),J=n?u.length===0:L+f.length===u.length,Z=[w.totals.failed===0,H,J,z.count===0,!z.truncated].every(Boolean),Ee=a.truncated||z.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,Xe=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",Ee,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:Z?["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.",Ee,...i.length>0&&p===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(G=>G!==void 0);return{ok:Z,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:L,abandoned:f.length,summaries:u.map(nn),missing_history_references_before:a.count,legacy_disposition_eligible:i.length,legacy_disposition_recorded:p,missing_history_references_after:z.count},validation:P,guidance:Xe,generated_at:P.generated_at}}import{createHash as qx}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3483e997-6bee-52bf-a048-8fe5c2427d06")}catch{}})();var nw=1,rw=/^[A-Za-z0-9_-]+$/,Kx=100,ew=1e3;var xH=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Je(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function zx(e){return qx("sha256").update(Yt({type:Je(e.type),author:Je(e.author),item:Je(e.item),harness:Je(e.harness),agent_instance:Je(e.agentInstance),provenance:Je(e.provenanceFilter)})).digest("hex").slice(0,24)}function tw(e,t){let n={version:nw,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function Hx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===nw,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function Bx(e,t){let n=e.trim();if(n.length===0||n.length>4096||!rw.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!Hx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function Vx(e){let t=e??Kx;if(!Number.isSafeInteger(t)||t<0||t>ew)throw new l(`Mutation event limit must be an integer from 0 to ${ew}.`,d.USAGE,{code:"invalid_event_limit"});return t}function Wx(e,t){let n=e?.trim();if(!n)return{};if(rw.test(n))return{cursor:Bx(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function Yx(e,t){let n=await qs(e,t);if(n===null){if(!await Au(e))return{...await Tu(e,t),source:"authoritative_history"};n=await qs(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function Jx(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Pi(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=Vx(e.limit),r=Jx(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let o=await A(t),a=o.agent_identity.identity_vocabulary,i=O_(o.agent_identity.harness_signals),s=x_({provenance:e.provenanceFilter},i),c=Je(e.harness),m=zx(e),{cursor:p,sinceTimestamp:u}=Wx(e.since,m),f={...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:Je(e.type),authors:Je(e.author),harnesses:c,harness_alias_authors:c?Object.entries(a.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:Je(e.agentInstance),provenance:[...s].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:Je(e.item),limit:n},_=await Yx(t,f),h=_.events.map(y=>({...r==="row"?{cursor:tw(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:P_(y.entry,a,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:tw(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:N_(_.events.map(y=>y.entry),a,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="015a3a52-f631-5ab7-b5c5-10a54a0b750c")}catch{}})();var Xx="1h",Qx="now",Zx="+1d";function qt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function ow(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return Ie(n,r)}async function aw(e,t,n,r){let o=ow(e,t,n),a=[];return qt(a,"start",n.start??Qx),n.end!==void 0?qt(a,"end",n.end):qt(a,"duration",n.duration??Xx),qt(a,"location",n.location),qt(a,"timezone",n.timezone),n.allDay===!0&&qt(a,"all_day","true"),o.event=[a.join(",")],Gt(o,r)}function iw(e,t,n){return aw("Meeting",e,t,n)}function sw(e,t,n){return aw("Event",e,t,n)}function cw(e,t,n){let r=ow("Reminder",e,t),o=[];return qt(o,"at",t.at??Zx),qt(o,"text",t.text??e),r.reminder=[o.join(",")],Gt(r,n)}import Hr from"node:crypto";import{cp as lw,lstat as eP,mkdir as yn,readFile as Qn,readdir as jl,rename as pw,rm as Kl,writeFile as Ni}from"node:fs/promises";import F from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3b4a5521-a665-5f60-8d01-16033b078916")}catch{}})();var uw="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var fw=F.join("runtime","workspace-snapshots"),tP=new Set(["checkpoints","locks","runtime","search","transactions"]),nP=/^[a-z0-9][a-z0-9._-]*$/,zr="sdk-workspace-transaction",Gl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},_w={renameEntry:pw,removeEntry:async e=>{await Kl(e,{recursive:!0,force:!0})}},ql=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Qn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==zr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ne(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
23
- `)}};async function hw(e,t=""){let n=await jl(F.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((a,i)=>a.name.localeCompare(i.name))){if(t.length===0&&tP.has(o.name))continue;let a=F.posix.join(t.replaceAll(F.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${a}`);if(o.isDirectory())r.push(...await hw(e,a));else if(o.isFile())r.push(a);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${a}`)}return r}async function gw(e){let t=await hw(e),n=Hr.createHash("sha256"),r=[],o=0;for(let i of t){let s=await Qn(F.join(e,i));r.push(s),o+=s.byteLength,n.update(i),n.update("\0"),n.update(String(s.byteLength)),n.update("\0"),n.update(s)}let a=n.digest("hex");return{manifest:{schema:uw,fingerprint:a,files:t,bytes:o},contents:r}}function dw(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
24
- `).filter(t=>t.trim().length>0).length}async function rP(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),a=await Promise.all(o.map(async i=>[i,await Qn(F.join(e,i))]));for(let[i,s]of a)n.set(i,s)}return n}function zl(e){if(!nP.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function yw(e,t){return ar(`workspace_snapshot_${e}`,t,{codes:{capacity:Gl.capacity.code,permission:Gl.permission.code,resource:Gl.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function wn(e){return F.join(e,fw)}function ww(e){return new l(`Unknown workspace snapshot: ${e}`,d.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function vw(e,t){try{return JSON.parse(await Qn(e,"utf8"))}catch(n){throw He(n)?ww(t):n}}async function mw(e,t,n){try{await Kl(e,{recursive:n})}catch(r){throw He(r)?ww(t):r}}async function oP(e,t,n=_w){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function aP(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(a){throw await r.renameEntry(n,t),await r.removeEntry(e),a}await r.removeEntry(n)}async function iP(e,t){return zl(t),/^[a-f0-9]{64}$/.test(t)?t:(await vw(F.join(wn(e),"refs",`${t}.json`),t)).fingerprint}async function Hl(e,t={}){if(t.name!==void 0&&(zl(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await gw(e),o=wn(e),a=F.join(o,"objects",n.fingerprint),i=!1;try{i=(await eP(a)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&He(s)))throw s}if(!i){let s=F.join(o,"objects",`.create-${process.pid}-${Hr.randomUUID()}`);await yw("create_object",async()=>{await yn(F.join(s,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let p=F.join(s,"files",m);await yn(F.dirname(p),{recursive:!0}),await Ni(p,r[c])}await Ni(F.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
25
- `,"utf8"),await yn(F.dirname(a),{recursive:!0})}),i=await oP(s,a)}if(t.name!==void 0){let s={name:t.name,fingerprint:n.fingerprint},c=F.join(o,"refs");await yn(c,{recursive:!0});let m=F.join(c,`.ref-${process.pid}-${Hr.randomUUID()}`);await Ni(m,`${JSON.stringify(s,null,2)}
26
- `,"utf8"),await pw(m,F.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Br(e,t){let n=await iP(e,t),r=await vw(F.join(wn(e),"objects",n,"manifest.json"),t);if(r.schema!==uw||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Bl(e){let t=wn(e),n=await jl(F.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&He(o))return[];throw o}),r=await jl(F.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&He(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Br(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Qn(F.join(t,"refs",o),"utf8"))))}}async function Vl(e,t){let n=await Br(e,t),{manifest:r,contents:o}=await gw(e),a=new Map(r.files.map((u,f)=>[u,o[f]])),i=await rP(F.join(wn(e),"objects",n.fingerprint,"files"),n.files),s=new Set(r.files),c=new Set(n.files),m=new Set([...s,...c]);for(let u of m){let f=a.get(u),_=i.get(u);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(u)}let p=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let f=dw(a.get(u)),_=dw(i.get(u));return{path:u,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(u=>u.removed_entries>0).sort((u,f)=>u.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...s].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!s.has(u)).length,removed_item_count:[...s].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:p.length,removed_history_entry_count:p.reduce((u,f)=>u+f.removed_entries,0),affected_history_streams:p,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function bw(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,a=n.lockWaitMs??5e3,i=await Te(e,zr,o,r,!1,!1,a),s=new ql(uo(e,zr),r,o);s.start(),await s.refreshNow();let c,m=!1,p=!1;try{let u=await Vl(e,t),f=await Br(e,t),_=await Hl(e),h=f.fingerprint,y=wn(e),g=F.join(y,"objects",h,"files"),w=F.dirname(e),b=F.basename(e);c=F.join(w,`.${b}.restore-${Hr.randomUUID()}`);let S=F.join(w,`.${b}.backup-${Hr.randomUUID()}`);await yw("restore_stage",async()=>{await yn(c,{recursive:!0}),await lw(g,c,{recursive:!0,force:!1}),await yn(F.join(c,"runtime"),{recursive:!0}),await lw(y,F.join(c,fw),{recursive:!0,force:!1})});let T=await Lu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:a}),L=F.relative(c,T.historyPath).replaceAll("\\","/");await s.stop(),p=!0;let P=uo(c,zr);return await yn(F.dirname(P),{recursive:!0}),await Ni(P,await Qn(uo(e,zr)),{flag:"wx"}),m=!0,await aP(c,e,S,_w,async()=>{s.start(),p=!1,await s.refreshNow()}),await s.stop(),p=!0,{manifest:f,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:L,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!m&&await Promise.allSettled([Kl(c,{recursive:!0,force:!0})]),u}finally{try{p||await s.stop()}catch{}finally{await i()}}}async function kw(e,t){zl(t);let n=wn(e);if(!/^[a-f0-9]{64}$/.test(t))return await mw(F.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Bl(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await mw(F.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f25e4f-09a1-554f-9e0b-a999fcce5c55")}catch{}})();function Vr(e){let t={...e.args,...e.options};return Ie(e.options,t)}function kt(e,t){let n=v(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Zn(e){return typeof e=="string"?[e]:ge(e)}function Sw(e){return Wy(Vr(e),e.global)}function Ew(e){let t=Vr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Pi({cwd:v(t,"cwd"),pmRoot:v(t,"path"),since:v(t,"since"),type:Zn(t.type),author:Zn(t.author),item:Zn(t.item),limit:t.limit===void 0?void 0:Fe(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Zn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Zn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Zn(t.provenanceFilter)}})}function Aw(e){let t=Vr(e),n=kt(t,"subcommand");if(n==="install")return gf({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Zy({dryRun:t.dryRun===!0,author:v(t,"author"),message:v(t,"message"),force:t.force===!0},e.global);if(n==="report")return l_({includeReconciled:t.includeReconciled===!0,cwd:v(t,"cwd")});if(n==="driver")return Jy({artifact:kt(t,"artifact"),basePath:kt(t,"basePath"),oursPath:kt(t,"oursPath"),theirsPath:kt(t,"theirsPath"),outputPath:v(t,"outputPath")??v(t,"output"),itemPath:v(t,"itemPath"),prefer:v(t,"prefer")},e.global);throw Ce({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Tw(e){let t=Vr(e),n=kt(t,"subcommand");if(n==="position")return U_(e.global);if(n!=="snapshot")throw Ce({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=v(t,"snapshotAction")??kt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return Hl(o,{name:v(t,"name")});if(r==="list")return Bl(o);let a=kt(t,"target");if(r==="inspect")return Br(o,a);if(r==="delete")return kw(o,a);if(r==="restore")return t.dryRun===!0?Vl(o,a):bw(o,a,{force:t.force===!0,author:v(t,"author"),message:v(t,"message"),lockTtlSeconds:Fe(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Fe(t.lockWaitMs,"lockWaitMs")});throw Ce({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Li(e){let t=Vr(e),n=kt(t,"title");return e.action==="meet"?iw(n,t,e.global):e.action==="event"?sw(n,t,e.global):cw(n,t,e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27bbfaed-a594-5b3b-84ba-431be02e002e")}catch{}})();function Cw(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:v(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ge(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:v(e,"measurementSource"),measurementItem:v(e,"measurementItem"),measurementRevision:v(e,"measurementRevision"),author:v(e,"author"),message:v(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:v(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import KP from"node:fs/promises";import Hw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function $i(e,t,n,r,o,a="min"){let i=o==="min"?e-t:t-e,s=a==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&s<0}function sP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,a=null,i=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let p;try{p=JSON.parse(m)}catch{continue}if(p===null||typeof p!="object"||!("ts"in p)||typeof p.ts!="string")continue;let u=p.ts,f=Date.parse(u);Number.isNaN(f)||($i(f,i,u,o,"min")&&(i=f,o=u),$i(f,s,u,a,"max","max")&&(s=f,a=u))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:a}}function Iw(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>sP(_,h)),a=0,i=0,s=null,c=null,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let _ of o){if(a+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);$i(h,m,_.id,s?.id??null,"min")&&(m=h,s={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);$i(h,p,_.id,c?.id??null,"max")&&(p=h,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:a,total_bytes:i,largest_by_bytes:u,deepest_by_lines:f,oldest_entry:s,newest_entry:c}}import{createHash as lP}from"node:crypto";import{execFile as dP}from"node:child_process";import xw from"node:path";import{promisify as mP}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Rw=1;function cP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Wl(e){if(e===null)return{format_version:Rw,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Rw||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!cP(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var pP=mP(dP),uP=50,Ow=1e3,fP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Pw(e){let t=e.trim().toLowerCase();if(!fP.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function _P(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Wr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function hP(e){let t=e??uP;if(!Number.isSafeInteger(t)||t<0||t>Ow)throw new l(`Improvement observation limit must be an integer from 0 to ${Ow}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Nw(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function gP(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Pw(n.metric),o=_P(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let a=await wP(e,n.revision),i=Wr(n.source,"source"),s=Wr(n.itemId,"itemId"),c=Wr(n.unit,"unit"),m=Wr(n.idempotencyKey,"idempotencyKey")??(a.revision_source==="unversioned"?void 0:[a.revision,r,i??"manual",s??"workspace"].join(":")),p={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Nw(n.observedAt??k(),"observedAt"),...a,author:C(n.author,t.author_default),...s===void 0?{}:{item_id:s},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:lP("sha256").update(Yt(p)).digest("hex").slice(0,24),...p}}function yP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function wP(e,t){let n=Wr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await pP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Qd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function vP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Lw(e,t={}){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await gP(n,r,e),a=xw.join(n,"improvement-ledger.json"),i=await aa({pmRoot:n,filePath:a,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:s=>{let c=Wl(s),m=yP(c,o);return m?{raw:s,result:m}:(c.observations.push(o),c.observations.sort((p,u)=>p.observed_at.localeCompare(u.observed_at)||p.metric.localeCompare(u.metric)||p.id.localeCompare(u.id)),{raw:`${Yt(c)}
27
- `,result:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function $w(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=e.metric===void 0?void 0:Pw(e.metric),r=e.since===void 0?void 0:Nw(e.since,"since"),o=hP(e.limit),a=Wl(await ee(xw.join(t,"improvement-ledger.json"))).observations.filter(s=>(n===void 0||s.metric===n)&&(e.itemId===void 0||s.item_id===e.itemId)&&(r===void 0||s.observed_at>=r)),i=new Map;for(let s of a){let c=i.get(s.metric)??[];c.push(s),i.set(s.metric,c)}return{observations:[...a].reverse().slice(0,o),total:a.length,truncated:a.length>o,trends:[...i].map(([,s])=>vP(s)).sort((s,c)=>s.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function Fw(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function bP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function kP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Yl(e=ur,t=xn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function SP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Jl(e,t=xn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let a of t){let i=`${o.agent_harness}\0${a}`,s=r.get(i)??{harness:o.agent_harness,dimension:a,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1;let c=o.agent_provenance?.[a];c!=null&&c.value.length>0?s.observed+=1:c===null?s.unavailable+=1:s.legacy_missing+=1,r.set(i,s)}return[...r.values()].map(o=>{let a=o.observed+o.unavailable;return{...o,coverage:a===0?null:o.observed/a,inert:a>=n&&o.observed===0}}).sort((o,a)=>o.harness.localeCompare(a.harness)||o.dimension.localeCompare(a.dimension))}function EP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let p=`${c.agent_harness}\0${m}`,u=o.get(p)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),o.set(p,u)}let a=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[p])=>m.localeCompare(p)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=a.filter(c=>c.entries>=r),s=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&s.length===0,minimum_coverage:n,minimum_entries:r,rows:a,failures:s}}function AP(e){let t=[...e].sort((a,i)=>a.ts.localeCompare(i.ts)||a.author.localeCompare(i.author)||a.op.localeCompare(i.op)||a.before_hash.localeCompare(i.before_hash)||a.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let a of t){let i=a.agent_episode,s=Fw(a),c=`${s.source}:${s.id}`,m=n.get(c);if(m){m.entries.push(a);continue}let p={id:s.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:s.source,entries:[a],children:[]};n.set(c,p),i!==void 0&&r.set(s.id,p)}let o=[];for(let a of n.values()){let i=a.parent_id?r.get(a.parent_id):void 0;i&&bP(a,i,r)?i.children.push(a):o.push(a)}return kP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var TP=1e4,Mw=1e5,CP=1e3,IP=30,RP=["append","comment","docs","file","learning","note","test_run"];function OP(e){let t=e??TP;if(!Number.isSafeInteger(t)||t<1||t>Mw)throw new l(`History analytics event limit must be an integer from 1 to ${Mw}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function Dw(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function xP(e){let t=e?.trim();if(!t)return new Date(Date.now()-IP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),a=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*a).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Uw(e,t){let n=OP(t.eventLimit),r=xP(t.since),o=[],a=r,i=!1;for(;o.length<n;){let s=await Pi({pmRoot:e,since:a,limit:Math.min(CP,n-o.length),full:!0}),c=s.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),i=s.has_more,a=s.next_cursor,!s.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:a}:{},source:"history_event_index"}}}function PP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function NP(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function LP(e){return RP.some(t=>e.startsWith(t))}function Gw(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function $P(e,t,n){let r=new Map,o=new Map,a=new Map;for(let i of t){let s=PP(i.entry,e),c=NP(i.entry),m=o.get(i.item_id)===!0,p=c===void 0?m:n.has(c);if(c!==void 0&&o.set(i.item_id,p),!s)continue;let u=Gw(r,s);u.events+=1,LP(i.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!m&&p?(u.closes+=1,a.set(i.item_id,s)):c!==void 0&&m&&!p&&(u.reopens+=1)}return{buckets:r,lastCloseValue:a}}function FP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(a=>a.kind==="discovered_from").map(a=>a.id));for(let a of o){let i=t.get(a);i&&(Gw(e,i).defectEscapes+=1)}}}function MP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function DP(e,t,n,r,o,a){let{buckets:i,lastCloseValue:s}=$P(e,t,r);return FP(i,s,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>MP(c,m,o,a)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function UP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),a=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(a)?1:Math.max(1,(a-o)/864e5)}function GP(e,t,n){let r=Yl(t),o=Jl(e,xn,n),a=o.filter(s=>s.inert).map(s=>({harness:s.harness,dimension:s.dimension,explicit_samples:s.observed+s.unavailable})),i=r.filter(s=>!s.covered).map(s=>s.dimension);return{descriptors:r,observations:o,inert:a,undeclared:i,warnings:[...a.map(s=>`provenance_dimension_inert:${s.harness}:${s.dimension}:${String(s.explicit_samples)}`),...i.map(s=>`provenance_dimension_undeclared:${s}`)]}}function jw(e,t=ur,n={}){let r=Dw(n.minimumSample);return{...GP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function qw(e,t,n,r={}){let o=Dw(r.minimumSample),a=UP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>DP(i,e.events,t,n,o,a)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var jP=32;function qP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let a=o.slice(0,o.indexOf("=")).trim();r.length>0&&a!=="unit"&&a!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Yr(e,t){let n=qP(e).map(r=>{let[o,...a]=r.split(","),i=o.indexOf("="),s=o.slice(0,i).trim(),c=o.slice(i+1).trim(),m=Number(c);if(i<=0||s.length===0||c.length===0||!Number.isFinite(m))throw new l(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,u;for(let f of a){let _=f.indexOf("="),h=f.slice(0,_).trim(),y=f.slice(_+1).trim();if(h==="unit"&&y.length>0)p=y;else if(h==="threshold"&&y.length>0&&Number.isFinite(Number(y)))u=Number(y);else throw new l(`Invalid --measure attribute "${f}"`,d.USAGE)}return{name:s,value:m,unit:p,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,jP)}function Kw(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function zw(e,t){let n=e.flatMap(a=>a.measurements??[]).filter(a=>a.name===t).sort((a,i)=>i.recorded_at.localeCompare(a.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function zP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function HP(e,t,n,r,o){let a=vr(e,"type",r),i=new Set(a.rows.map(u=>u.key)),s=t.filter(u=>!i.has(u)),c=(o?[...a.rows,...s.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:a.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),m=zP([...n]);for(let u of e)m[u.status]+=1;let p=Object.fromEntries(Object.entries(m).filter(([,u])=>o||u>0));return{byType:c,byStatus:p,omitted:o?0:s.length+Object.values(m).filter(u=>u===0).length}}function BP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function VP(e){let t=Hw.join(e,"history");if(!await j(t))return[];await Rn({path:t,scope:"project"});let n=(await KP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,a)=>o.localeCompare(a)),r=[];for(let o of n){let a=Hw.join(t,o),i=await ee(a);i!==null&&(await Rn({path:a,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function WP(e,t){let n=[],r=k();for(let o of Yr(t.observe,r))n.push(await Lw({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function YP(e,t,n){let r={};return t.byAssignee&&(r.assignee=vr(e,"assignee",n)),t.byTag&&(r.tag=vr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=vr(e,"priority",n)),r}async function JP(e,t,n,r,o){let a={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await Uw(e,a):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?jw(i,n.agent_identity?.harness_signals,a):void 0,fleetAttribution:o.fleetAttribution&&i?qw(i,t,r,a):void 0}}function XP(e,t,n,r,o){let a=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...a?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Xl(e,t={}){let n=E(process.cwd(),e.path);await I(n);let r=await A(n),o=await WP(e,t),a=x(r,O()),i=$(r.schema),s=t.fieldUtilization?await Qu(n,r.item_format,a.type_to_folder,void 0,r.schema):await fe(n,r.item_format,a.type_to_folder,void 0,r.schema);await zu({pmRoot:n,settings:r,itemIds:s.map(S=>S.id),commandLabel:"stats"});let c=Sa(i),m=HP(s,a.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),p=await VP(n),u=0;for(let S of p)u+=BP(S.raw);let f=t.storage?Iw(p):void 0,_=t.metadataCoverage?sf(s,c):void 0,h=YP(s,t,c),y=t.fieldUtilization?cf(s):void 0,g=t.measurements===!0||o.length>0?await $w({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:b}=await JP(n,s,r,i.terminal_statuses,t);return XP({items:s.length,history_streams:p.length,history_entries:u},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:o,provenanceCoverage:w,fleetAttribution:b})}import QP from"node:fs/promises";import Kt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a41eaff2-6a15-5e82-b3aa-03ca48fc3eb5")}catch{}})();var Xw=Kt.join("runtime","telemetry","events.jsonl"),Qw=Kt.join("runtime","telemetry","state.json"),ZP=Kt.join("runtime","telemetry"),eN=20,Zw=Jt.filter(e=>e.lifecycle==="deprecated"),Bw=["status","flush","stats","clear"],Vw=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Ql=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Ww=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},tN=e=>({command:Ql(e.event.command,"<unknown>"),eventType:Ql(e.event.event_type,"unknown"),eventSchemaVersion:Ww(e.event.schema_version),clientSchemaVersion:Ww(e.client_schema_version)}),nN=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),rN=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},oN=e=>{let t=e?.command_resolution;return Ql(t,"")||void 0},ev=(e,t)=>{e[t]=(e[t]??0)+1},aN=(e,t)=>{let n=rN(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=oN(t);r!==void 0&&ev(e.resolution_counts,r)},iN=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Yw=(e,t)=>{t!==void 0&&e.add(t)},sN=(e,t)=>{let n=tN(t),r=e.get(n.command)??nN();r.count+=1,r.max_attempts=Math.max(r.max_attempts,iN(t.attempts)),ev(r.event_type_counts,n.eventType),Yw(r.event_schema_versions,n.eventSchemaVersion),Yw(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&aN(r,t.event.payload),e.set(n.command,r)},cN=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((a,i)=>a-i),o=Object.entries(t.resolution_counts).sort((a,i)=>a[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((a,i)=>a[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((a,i)=>a-i),client_schema_versions:[...t.client_schema_versions].sort((a,i)=>a-i),...r.length>0?{duration_p50_ms:Vw(r,.5),duration_p95_ms:Vw(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},lN=e=>{let t=(e??"status").trim().toLowerCase();if(Bw.includes(t))return t;throw Ce({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Bw,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},ed=()=>{throw new l("--limit must be a positive integer",d.USAGE)},tv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?ed():e,dN=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?ed():tv(Number.parseInt(t,10))},mN=e=>e===void 0?eN:typeof e=="number"?tv(e):typeof e=="string"?dN(e):ed(),pN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},uN=e=>{try{let t=JSON.parse(e);return pN(t)?t:void 0}catch{return}},fN=e=>e===null?[]:e.split(`
28
- `).map(t=>t.trim()).filter(t=>t.length>0),nv=e=>{let t=fN(e),n=[],r=0;for(let o of t){let a=uN(o);a===void 0?r+=1:n.push(a)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},_N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hN=e=>{try{let t=JSON.parse(e);return _N(t)?t:{}}catch{return{}}},Zl=async e=>{let t=await ee(e);return t===null||t.trim().length===0?{}:hN(t)};function gN(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function yN(e,t,n){let r=Object.create(null);for(let[o,a]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof a!="object"||a===null||Array.isArray(a))continue;let i=a;!Number.isSafeInteger(i.count)||i.count<1||typeof i.last_seen!="string"||!i.last_seen.startsWith(o)||(r[o]={count:i.count,last_seen:i.last_seen})}return r}function Jw(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let a of Zw){let i=r[a.alias];if(typeof i!="object"||i===null||Array.isArray(i))continue;let s=i;if(s.canonical!==a.canonical||typeof s.days!="object"||s.days===null||Array.isArray(s.days))continue;let c=yN(s.days,t,o);Object.keys(c).length>0&&(n[a.alias]={canonical:a.canonical,days:c})}return n}async function wN(e,t,n){let r=gN(n),o=await Zl(t),a=Jw(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(a))return a;try{await Zs(async()=>{let i=await Zl(t);if(i.alias_usage===void 0)return;let s=Jw(i.alias_usage,r);JSON.stringify(i.alias_usage)!==JSON.stringify(s)&&await ne(t,`${JSON.stringify({...i,alias_usage:s},null,2)}
29
- `)},e,250)}catch{}return a}var Fi=e=>e??null,Mi=async e=>{let t=await A(e),n=Kt.join(e,Xw),r=Kt.join(e,Qw),o=await ee(n),a=nv(o),i=await Zl(r),s=tf();return{enabled:t.telemetry.enabled&&!s.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:s,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:a.rows_total,queue_entries:a.valid_entries,queue_invalid_rows:a.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:Fi(i.last_attempted_flush_at),last_successful_flush_at:Fi(i.last_successful_flush_at),last_failed_flush_at:Fi(i.last_failed_flush_at),last_failed_flush_error:Fi(i.last_failed_flush_error)}},vN=e=>{let t=new Map;for(let n of e)sN(t,n);return[...t.entries()].map(([n,r])=>cN(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},bN=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Mi(t.globalPmRoot),generated_at:k()}),kN=async(e,t)=>{let n=await Mi(t.globalPmRoot);await of(t.globalPmRoot);let r=await Mi(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),a=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:a,queue_drained:a,status:r,generated_at:k()}},SN=async(e,t)=>{let n=mN(e.limit),r=await ee(t.queuePath),o=nv(r),a=vN(o.entries),i=a.slice(0,n),s=await A(t.globalPmRoot),c=await wN(t.globalPmRoot,t.statePath,s.telemetry.retention_days),m=Object.entries(c).map(([p,u])=>{let f=Object.values(u.days);return{alias:p,canonical:u.canonical,count:f.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:f.map(_=>_.last_seen).sort().at(-1)}}).sort((p,u)=>u.count-p.count||p.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:a.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:a.length>i.length,stats:i,alias_usage:m,zero_use_aliases:Zw.map(p=>p.alias).filter(p=>c[p]===void 0),alias_usage_retention_days:s.telemetry.retention_days,generated_at:k()}},EN=async(e,t)=>Zs(async()=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await $e(t.globalPmRoot,n,"telemetry:clear");let o=Kt.join(t.globalPmRoot,ZP),a=await j(o);return await QP.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:a&&!await j(o),queue_exists_after:await j(t.queuePath),state_exists_after:await j(t.statePath),status:await Mi(t.globalPmRoot),generated_at:k()}},t.globalPmRoot),AN={status:bN,flush:kN,stats:SN,clear:EN};async function rv(e,t){let n=lN(e.subcommand),r=lt(process.cwd());return AN[n](e,{globalPmRoot:r,queuePath:Kt.join(r,Xw),statePath:Kt.join(r,Qw)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var ov=20;function TN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ov;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ov:t}function td(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let a=Xo(r.recorded_at,o.recorded_at);if(a!==0)return a;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=TN();return t.length>n?t.slice(t.length-n):t}async function Di(e){await ce({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=td([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function av(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function nd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=av(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let a of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof a=="number"&&(!Array.isArray(o)||a>=o.length))return{found:!1,value:void 0};let i=Object.getOwnPropertyDescriptor(o,a);if(!i||!Object.hasOwn(i,"value"))return{found:!1,value:void 0};o=i.value}return{found:!0,value:o}}import{cp as CN,lstat as IN,mkdir as RN,readlink as ON,realpath as od,stat as xN,symlink as iv}from"node:fs/promises";import K from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d27093d8-5bac-5dcf-8334-07c8b8bc93a7")}catch{}})();var PN=new Set([".agents",".git",".nyc_output",".turbo","coverage"]);function rd(e){return e.split(K.sep).some(t=>PN.has(t.toLowerCase()))}function Jr(e){return e===".."||e.startsWith(`..${K.sep}`)||K.isAbsolute(e)}async function sv(e){try{return await xN(e)}catch(t){if(!He(t))throw t;return}}async function Ui(e){let t=[],n=e;for(;K.dirname(n)!==n;)try{return K.join(await od(n),...t)}catch(r){if(!He(r))throw r;t.unshift(K.basename(n)),n=K.dirname(n)}return K.join(await od(n),...t)}async function NN(e,t,n){let r=K.relative(t,await Ui(e));if(!Jr(r))return r;let o=[],a=e;for(;K.dirname(a)!==a;){let i=await Ui(a),s=n.find(([,c])=>c===i);if(s)return K.join(s[0],...o);o.unshift(K.basename(a)),a=K.dirname(a)}return r}async function cv(e,t){let n=[],r=[],o=await od(e),a=await Ui(K.resolve(t));if(![K.relative(o,a),K.relative(a,o)].every(Jr))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await RN(K.dirname(t),{recursive:!0}),await CN(o,t,{recursive:!0,force:!0,async filter(i){let s=K.relative(o,i);if(!s)return!0;if(rd(s))return!1;if(K.basename(i).toLowerCase()==="node_modules"){if((await sv(i))?.isDirectory()){let c=await Ui(i),m=K.relative(o,c);if(!Jr(K.relative(c,o))||!Jr(m)&&(rd(m)||!m.split(K.sep).some(p=>p.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${s}`);n.push([s,c])}return!1}return(await IN(i)).isSymbolicLink()?(r.push([s,K.resolve(K.dirname(i),await ON(i)),(await sv(i))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[i]of n)await iv(K.resolve(o,i),K.join(t,i),"junction");for(let[i,s,c]of r){let m=await NN(s,o,n);if(Jr(m)||rd(m))throw new Error(`Source symlink must target included workspace source: ${i}`);await iv(K.resolve(t,m),K.join(t,i),c)}}import{spawn as Cv}from"node:child_process";import{cp as pv,mkdir as dd,mkdtemp as Iv,open as sd,readdir as cd,rm as Xr,symlink as MN}from"node:fs/promises";import{tmpdir as Rv}from"node:os";import ae from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var lv=100;function ad(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function LN(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=lv?t:`${t.slice(0,lv-3)}...`}function dv(e){return e.map((t,n)=>`${n+1}. ${LN(t)}`).join("; ")}function $N(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function FN(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function mv(e,t){let n=$N(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,a)=>a+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let a=[],i=[];for(let s=0;s<e.length;s+=1)FN(e[s],o)&&(i.push(e[s]),a.push(s+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${dv(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:a,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=ad(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${dv(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6700ed53-3964-5cc4-ab5e-9759acefdae2")}catch{}})();var qi=20*1024*1024,DN=3e3,UN=1e4,GN=5e3,uv=120,jN=new Set(["locks","extensions","runtime"]),qN=new Set(["history","index","search","extensions","locks","runtime"]),KN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],zN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,HN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,BN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function md(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function VN(){return md("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",DN)}function WN(){return md("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",UN)}function YN(){return md("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",GN)}function JN(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function XN(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function pd(e){let t=0,n=0,r=0,o=0;for(let a of e){let i=a.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function QN(e){let t=e??"project";if(!ct.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function Ki(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(cn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${cn.join(", ")}`,d.USAGE)}function ZN(e){return dn(e??"source","--workspace-context")}function Ov(e,t,n){return n?t:dn(e.workspace_context_mode,"linked test")??t}function xv(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ki(e.pm_context_mode)}function Pv(e,t){return e==="auto"?t?"tracker":"schema":e}function eL(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function tL(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function nL(e,t){let n={};if(!e)return n;for(let r of e){let o=Mr(r,t);if(o)for(let[a,i]of Object.entries(o))n[a]=i}return n}function rL(e,t){if(!e)return[];let n=[];for(let r of e){let o=Dr(r,t);o&&n.push(...o)}return[...new Set(n)]}function oL(e){let t=zi(e);return Cr(t).some(n=>cc(n)!==null)}function Nv(e){let t=zi(e);return Cr(t).some(n=>{let r=cc(n);if(!r)return!1;let o=k_(r);return o?BN.has(o.subcommand):!1})}function Gi(e){if(e)return w_.has(e.subcommand)?Kn(e.args,v_)?.subcommand:e.subcommand}function fv(e,t){if(e==="npx"||e==="bunx")return Ma(t)?.command;if(e==="pnpm")return Gi(Kn(t,__));if(e==="npm")return Gi(Kn(t,h_));if(e==="yarn")return Gi(Kn(t,g_));if(e==="bun")return Gi(Kn(t,y_))}function ji(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function id(e){return!e||!dc(e.command)&&!b_(e.command)?!1:Fa(e.args)==="test-all"}var Lv=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),aL=new Set(["npx","bunx"]);function $v(e){let t=e.split(" ").filter(i=>i.length>0),n=lc(t);if(n.length===0)return!1;let[r,...o]=n,a=Lv.get(r);if(a){let i=o.findIndex(s=>a.test(s));return i>=0?$v(o.slice(i+1).join(" ")):!1}return dc(r)||mc(r)?Fa(o)==="test-all":r==="node"&&o.length>0&&mc(o[0])?Fa(o.slice(1))==="test-all":aL.has(r)?id(Ma(o)):r==="pnpm"?id(pc(o)):r==="npm"?id(uc(o)):!1}function Fv(e){let t=zi(e);return Cr(t).some(n=>$v(n))}function Mv(e){if(Fv(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function zi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Dv(e){let t=e.split(" ").filter(i=>i.length>0),n=lc(t);if(n.length===0)return!1;let[r,...o]=n,a=Lv.get(r);if(a){let i=o.findIndex(s=>a.test(s));return i>=0&&Dv(o.slice(i+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?iL(o):sL(r,o)}function iL(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function sL(e,t){return e==="npx"||e==="bunx"?ji(Ma(t)?.command):e==="pnpm"||e==="npm"?ji((e==="pnpm"?pc(t):uc(t))?.command)||ji(fv(e,t)):(e==="yarn"||e==="bun")&&ji(fv(e,t))}function cL(e){if(Fv(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function lL(e){return e?e.map(dL):[]}function dL(e){let t=e.trim(),n=yg(t)?oi(de(e,"--add"),"--add"):{command:t},r=he(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Mv(r),{command:r,path:he(n.path),scope:QN(n.scope),timeout_seconds:mL(he(n.timeout_seconds),he(n.timeout)),pm_context_mode:li(he(n.pm_context_mode),"--add"),workspace_context_mode:dn(he(n.workspace_context_mode),"--add"),env_set:Mr(he(n.env_set),"--add"),env_clear:Dr(he(n.env_clear),"--add"),shared_host_safe:ci(he(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:mn(he(n.assert_stdout_contains)),assert_stdout_regex:Vn(he(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:mn(he(n.assert_stderr_contains)),assert_stderr_regex:Vn(he(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:di(he(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:mi(he(n.assert_json_field_equals),"--add"),assert_json_field_gte:pi(he(n.assert_json_field_gte),"--add"),note:he(n.note)}}function he(e){let t=e?.trim();return t&&t.length>0?t:void 0}function mL(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ue(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function pL(e){return e?e.flatMap(t=>{let n=bg(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);Mv(o)}return n}):[]}function uL(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=de(n,"--remove"),a=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:a,value:i.trim()}}return{kind:"either",value:n}}):[]}function fL(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function _L(e){try{e.stdin?.end()}catch{}}function Uv(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=uv?t:`${t.slice(0,uv-3)}...`}function Gv(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function ld(e){try{process.stderr.write(`${e}
30
- `)}catch{}}function hL(e,t){if(!Gv(t))return null;let n=Uv(e.command),r=Date.now();ld(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let a=Date.now()-r;ld(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${a} command="${n}"`)},WN());return o.unref?.(),o}function gL(e,t,n,r){if(!Gv(r))return;let o=Uv(e.command),a=Date.now()-n,i=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",s=[];t.timedOut&&s.push("reason=timeout"),t.maxBufferExceeded&&s.push("reason=max_buffer"),t.outputTruncated&&s.push("output=truncated"),t.signal&&s.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),m=s.length>0?` ${s.join(" ")}`:"";ld(`[pm test] linked-test ${e.index}/${e.total} end status=${i} exit_code=${c} elapsed_ms=${a}${m} command="${o}"`)}async function _v(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Cv("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function yL(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function wL(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await _v(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{_v(r)},VN()),t.forceKillTimer.unref?.()}}function vL(e){return new Promise(t=>{let n=!1,r=null,o=(a,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(a))};e.on("exit",(a,i)=>{n||(r=setTimeout(()=>{o({code:a,signal:i},!0)},YN()),r.unref?.())}),e.on("close",(a,i)=>{o({code:a,signal:i})})})}function bL(e,t,n,r,o){return Cv(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function hv(e){let t=await sd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,qi),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>qi}}finally{await t.close()}}async function kL(e,t,n,r,o,a=process.cwd()){let i=Date.now(),s=await Iv(ae.join(Rv(),"pm-linked-test-output-"));try{let c=ae.join(s,"stdout.log"),m=ae.join(s,"stderr.log"),[p,u]=await Promise.all([sd(c,"w"),sd(m,"w")]),f;try{f=bL(e,n,p.fd,u.fd,a)}catch(H){throw await Promise.all([p.close(),u.close()]),H}let _=vL(f),h;f.on("error",H=>{h=H.message}),await Promise.all([p.close(),u.close()]),_L(f);let y={heartbeat:hL(r,o),forceKillTimer:null,timedOutTimer:null},g=wL(f,y),w=!1;y.timedOutTimer=setTimeout(()=>{w=!0,g()},t),y.timedOutTimer.unref?.();let{code:b,signal:S}=await _;yL(y);let[T,L]=await Promise.all([hv(c),hv(m)]),P=T.truncated||L.truncated,M=P?`
20
+ `,{changedFields:["body"]}}});return{item:c.item,appended:s,changed_fields:c.changedFields}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f7d8635-ea1c-5c87-9001-bfa1d1618478")}catch{}})();var bT=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function cg(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function Kc(e,t){return zc(e,t,{operation:"close"})}function zc(e,t,n){let r=cg(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Hc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],a=o.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,s=[];if(r&&(delete e.blocked_by,s.push("blocked_by")),i&&(delete e.blocked_reason,s.push("blocked_reason")),t.orderingEdges==="remove"&&a.length>0){let m=new Set(a),p=o.filter(u=>!m.has(u));p.length>0?e.dependencies=p:delete e.dependencies,s.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:s,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...a.length>0?[`closed_removed_predecessors:${e.id}:${a.map(m=>m.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${a.length}`]:[]]};let c=[...new Set([...n?[n]:[],...a.map(m=>m.id)])];return c.length===0?{changedFields:s,warnings:[]}:{changedFields:s,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab15186d-b8bc-5740-bc16-d5af1eeeaa02")}catch{}})();var kT=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function ST(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function lg(e){let t=[];for(let n of kT){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function dg(e,t,n={}){let r=lg(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},a=r.map(s=>`--${s.key.replaceAll("_","-")}`),i=["--pm-path",t,"update",e.id,...r.flatMap((s,c)=>[a[c],o[s.key]?.trim()||"<value>"])];return{missing:a,suggested_retry:Zt(i),suggested_retry_args:i}}async function ET(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let a=o.trim();if(a===n)return!0;if(r.has(a))return!1;r.add(a),o=(await e(a))?.duplicate_of}return!1}function AT(e){return typeof e!="string"||e.trim().length===0}async function TT(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let a=x(t,O()),i=new Map,s=async m=>{if(i.has(m))return i.get(m)??null;let p=await q(e,m,t.id_prefix,t.item_format,a.type_to_folder);if(!p)return i.set(m,null),null;let{document:u}=await se(p,{schema:t.schema});return i.set(m,u.metadata),u.metadata},c=await s(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,d.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await ET(s,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,d.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function CT(e,t,n){return e.filter(r=>r.parent===t&&!oe(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function IT(e,t,n){let r=new Map(e.map(s=>[s.id.trim().toLowerCase(),s])),o=af(e),a=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(s=>i.has(s.status)).map(s=>({item:s,blockerIds:o.get(s.id.trim().toLowerCase())})).filter(({blockerIds:s})=>s.includes(a)).filter(({blockerIds:s})=>s.every(c=>{if(c===a)return!0;let m=r.get(c);return m!==void 0&&oe(m.status,n)})).map(({item:s,blockerIds:c})=>({id:s.id,blocker_ids:c})).sort((s,c)=>s.id.localeCompare(c.id))}async function RT(e,t,n,r,o,a){let i=IT(n,r,a),s=[];for(let c of i)try{let m=await ce({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(p){let u=p.metadata.dependencies??[],f=u.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});p.metadata.status=a.open_status,delete p.metadata.blocked_by,delete p.metadata.blocked_reason,p.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?p.metadata.dependencies=f:delete p.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==u.length&&_.push("dependencies"),{changedFields:_}}});s.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let p=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";s.push(`auto_unblock_failed:${c.id}:${p}`)}return s}function OT(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:a}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[a]=i,n.push(a))}return n}function xT(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:a}of r)AT(e[o])&&(e[o]=a,n.push(o));return n}function PT(e,t,n,r){let o=[];if(t!=="off"){let a=lg(e);if(a.length>0){let i=a.map(s=>s.label);if(t==="strict"){let s=a.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...s.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:s,suggested_retry:Zt(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function NT(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function LT(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function $T(e,t){if(oe(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,d.CONFLICT,{recovery:dg(e,t.pmRoot,t.options)});let n=OT(e,t.options),r=xT(e,t.duplicateOf),o=PT(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let a=t.options.completedAt!==void 0||e.completed_at===void 0;a&&(e.completed_at=t.completedAt);let i=["status","closed_at",...a?["completed_at"]:[],...NT(e,t.closeReason),...n];if(rf(e)&&(e.plan_mode="completed",i.push("plan_mode")),t.duplicateOf!==void 0){i.push("duplicate_of");for(let c of r)i.includes(c)||i.push(c)}i.push(...LT(e));let s=Hc(e,t.lifecyclePolicy);return i.push(...s.changedFields),o.push(...s.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function mg(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let a=await A(o),i=$(a.schema),s=C(n.author,a.author_default),c=x(a,O()).type_to_folder,m=await q(o,e,a.id_prefix,a.item_format,c);if(!m)throw await _t(o,e,a.id_prefix,c);let p=await TT(o,a,n.duplicateOf,m.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??a.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Kc({explicit:t,duplicateOf:p,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,_=ST(n.validateClose)??a.governance.close_validation_default,h=await fe(o,a.item_format,c,void 0,a.schema),y=CT(h,m.id,i),g=k(),w=n.completedAt===void 0?g:ie(n.completedAt,new Date(g),"completed-at"),b=await ce({pmRoot:o,settings:a,id:m.id,op:"close",author:s,message:n.message,force:n.force,mutate(T){return $T(T.metadata,{pmRoot:o,statusRegistry:i,force:n.force,options:n,duplicateOf:p,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:w,lifecyclePolicy:u})}}),S=_==="warn"?dg(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...S?{recovery:S}:{},warnings:[...b.warnings,...await RT(o,a,h,m.id,s,i)]}}function wt(e,t,n,r){return mg(e,t,n,r)}import FT from"fast-json-patch";import Bc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebfa0c5e-461b-5078-8272-69086e84b4dc")}catch{}})();async function pg(e,t,n){let r=await Xu(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:ug(n),recovered:!0}}function MT(e,t){return Wu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function ug(e){let t=Zs(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:rt(ot(t))}async function DT(e,t,n,r){let o=await tn(e,t,n,r),a=o.located?await Ku({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:a.warnings}}function UT(e,t){let n=_r(e),r=_r(t),o=FT.compare(n,r),a=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){a.add("body");continue}let s=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];a.add(s.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(a).sort((i,s)=>i.localeCompare(s))}async function GT(e){let t=await __({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>pg(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function jT(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:ug(t),originalRaw:null}}function qT(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function KT(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ne(e.existingItemPath,e.resolvedOriginalRaw),await Bc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ne(e.existingItemPath,e.resolvedOriginalRaw);return}await Bc.rm(e.restoredItemPath,{force:!0})}async function zT(e){return[...await Y({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Y({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function an(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let a=await A(o),i=x(a,O()),s=await DT(o,e,a,i.type_to_folder),c=s.id,{raw:m,entries:p}=await Eu(s.historyPath,c);if(p.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let u=MT(t,p),f=Yu(Zs(p,u.historyIndex),u),_=Nu(f,{schema:a.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let h=(s.located?await pg(s.located,a,p):null)?.raw??null,y=C(n.author,a.author_default),g=await Te(o,c,a.locks.ttl_seconds,y,!!n.force,a.governance.force_required_for_stale_lock,a.locks.wait_ms);try{let{loadedItemUnderLock:w,existingItemPath:b}=await GT({pmRoot:o,subject:s,settings:a,typeRegistry:i,historyRawBeforeLock:m,currentItemRawBeforeLock:h,history:p}),S="toon",T=jT(w,p),L=qT({document:T.document,author:y,force:n.force,enforcement:a.governance.ownership_enforcement,resolvedId:c}),P=UT(T.document,_),M=await yr({pmRoot:o,settings:a,operation:"restore",author:y,before:T.document,after:_});await Wo({pm_root:o,operation:"restore",before:T.document,after:_,changed_fields:P,sdk:ka({pmRoot:o,settings:a,typeToFolder:i.type_to_folder})});let z=Be(_,{format:S,schema:a.schema}),H=dt(o,_.metadata.type,c,S,i.type_to_folder),J=await $t(o,y),ee=[];try{await ne(H,z),b&&H!==b&&await Bc.rm(b);let pe=$e({nowIso:k(),author:y,op:"restore",before:T.document,after:_,message:n.message,context:M.decisions.length===0?void 0:{workflow_policies:M.decisions}});try{await xt(s.historyPath,pe)}catch(Ze){throw await KT({existingItemPath:b,resolvedOriginalRaw:T.originalRaw,restoredItemPath:H}),Ze}ee=await Ft({pmRoot:o,preferredFormat:a.item_format,typeToFolder:i.type_to_folder,schema:a.schema,itemPath:H,previousItemPath:b??void 0,document:_})}finally{await J()}let Ee=await zT({restoredItemPath:H,historyPath:s.historyPath,before:T.document,after:_});In({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:T.document.metadata.status,status:_.metadata.status,previous:Qt(T.document.metadata,P),current:Qt(_.metadata,P),changed_fields:P});let Qe=p[u.historyIndex],G=Mn(p,!0);return{item:_.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:G===null?null:G+u.historyIndex+1,entry_ts:Qe.ts,entry_op:Qe.op},changed_fields:P,warnings:[...M.warnings,...w?.recovered?["restore_unreadable_item_recovered"]:[],...s.historyPolicyWarnings,...L,...ee,...Ee]}}finally{await g()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6edfa77d-9b76-540b-a365-a3fef0450c53")}catch{}})();var _g=1,Vc="close-many",HT=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function BT(e,t){return Cr(e,t,{includePagination:!1})}function VT(e,t){return Cr(e,t)}function WT(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function YT(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function JT(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.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 XT(e,t){let n=$(t.schema),r=x(t,O()),o=await fe(e,t.item_format,r.type_to_folder,void 0,t.schema),a=new Map,i=new Map;for(let s of o){if(typeof s.parent!="string"||s.parent.length===0||(i.set(s.id,s.parent),oe(s.status,n)))continue;let c=a.get(s.parent);c?c.push(s.id):a.set(s.parent,[s.id])}for(let s of a.values())s.sort((c,m)=>c.localeCompare(m));return{childrenByParent:a,parentByChild:i}}function fg(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,a=t.get(e),i=[],s=new Set,c=!1;for(;a!==void 0&&!s.has(a);){let m=n?.get(a);if(m!==void 0){o+=m+1;break}s.add(a),i.push(a),o+=1,a=t.get(a)}if(a!==void 0&&s.has(a)&&(c=!0),!c){n?.set(e,o);for(let[m,p]of i.entries())n?.set(p,o-m-1)}return o}async function QT(e){let t=await ca(e.pmRoot,Vc,e.rollbackId,_g),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await la(t.items,(o,a)=>an(o,a,{author:e.options.author,message:n,force:!0},e.global));return{...en({applied:r.restored_ids.length,skipped:0,failed:r.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:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function ZT(e,t,n,r,o){return e.map(a=>{let i=(t.get(a.id)??[]).filter(c=>!n.has(c)),s=!hg(a,r,o);return{id:a.id,title:typeof a.title=="string"?a.title:"",status:a.status,action:s?"skip":"close",...s?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function eC(e){let t=await sa(e.pmRoot,Vc,e.checkpointId,{schema_version:_g,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 tC(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await wt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:An(o)})}}return{rows:t,closedIds:n}}function nC(e){return typeof e.rollback=="string"?e.rollback:void 0}function rC(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(VT(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function oC(e){if(!BT(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${HT}). Refusing to match every item.`,d.USAGE)}function aC(e,t){let n=new Map;return[...e].sort((r,o)=>{let a=fg(o.id,t,n)-fg(r.id,t,n);return a!==0?a:r.id.localeCompare(o.id)})}function hg(e,t,n){return n||!oe(e.status,t)}function iC(e,t,n){return new Set(e.filter(r=>hg(r,t,n)).map(r=>r.id))}async function sC(e){oC(e.options);let t=$(e.settings.schema),n=JT(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ht(e.options.status,YT(e.options.list),e.global),{childrenByParent:a,parentByChild:i}=await XT(e.pmRoot,e.settings),s=aC(o.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await ht(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,p=new Set(m.map(f=>f.id)),u=iC(s,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:s,unmatchedIds:c.length===0?void 0:c.filter(f=>!p.has(f)),planRows:ZT(s,a,u,t,r)}}function cC(e){return{outcome:"effect",exit_code:d.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 lC(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 eC({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 gg(e,t){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=e.dryRun===!0,a=nC(e);if(WT(e.list),a!==void 0)return rC(e,a),QT({pmRoot:n,rollbackId:a,options:e,global:t});let i=await sC({pmRoot:n,settings:r,options:e,global:t});if(o)return cC(i);let s=new Set(i.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=k(),m=ia(Vc,c),p=await lC({context:i,options:e,closableIds:s,checkpointId:m,nowValue:c}),u={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await tC({matched:i.matched,closableIds:s,reason:i.reason,closeOptions:u,global:t}),h=f.filter(w=>w.status==="closed").length,y=f.filter(w=>w.status==="skipped").length,g=f.filter(w=>w.status==="failed").length;return{...en({applied:h,skipped:y,failed:g,unmatched:i.unmatchedIds?.length??0}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...p?{checkpoint:p}:{},closed_count:h,skipped_count:y,failed_count:g,rows:f,ids:_,...i.unmatchedIds!==void 0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="902e9f78-a2c1-59bb-aaa2-763576d5c68b")}catch{}})();function dC(e,t){return[...new Set([...so.filter(n=>e[n]!==void 0),...Object.keys(e).filter(n=>e[n]!==void 0),...t.length>0?["body"]:[]])].sort((n,r)=>n.localeCompare(r))}function mC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Wc(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),a=x(o,O()),i=await q(r,e,o.id_prefix,o.item_format,a.type_to_folder);if(!i)throw await _t(r,e,o.id_prefix,a.type_to_folder);let s=await se(i,{schema:o.schema}),c=s.document.metadata,m=k(),p=C(t.author,o.author_default),u=await hr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:a.type_to_folder,probeExisting:!1}),f=$(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:u,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=Tt(O()),g=rt({metadata:h,body:s.document.body},{schema:o.schema,extensionFieldNames:y}),w=await qn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),b=dC(g.metadata,g.body),S=dt(r,g.metadata.type,u,o.item_format,a.type_to_folder),T=tt(r,u),L=await Te(r,u,o.locks.ttl_seconds,p,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),P={metadata:{},body:""},M,z;try{let H=await $t(r,p,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await qn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let J=await q(r,u,o.id_prefix,o.item_format,a.type_to_folder);if(J)throw new l(`Cannot copy to ${u}: an item with that id already exists at ${J.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${u} already exists at ${J.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await ne(S,Be(g,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let ee=$e({nowIso:m,author:p,op:"create",before:P,after:g,message:mC(i.id,t.message)});await xt(T,ee)}catch(ee){throw await En(S),ee}z=await Ft({pmRoot:r,preferredFormat:o.item_format,typeToFolder:a.type_to_folder,schema:o.schema,itemPath:S,document:g})}finally{await H()}M=[...await Y({path:S,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:P,after:g,changed_fields:b}),...await Y({path:T,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:P,after:g,changed_fields:b})],In({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Qt(g.metadata,b),changed_fields:b})}finally{await L()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:b,warnings:[...Pa(w),...z,...M],...w===void 0?{}:{similarity_advisory:w}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c8f85c4-33c4-5e7d-b01d-b95c8281250d")}catch{}})();var pC="hierarchy-integrity";async function Ja(e){let t=e.required?await Te(e.pmRoot,pC,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Xa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Qa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Za(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(io.includes(t))return t;let n=ue(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function ei(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c22dc1f8-285a-5858-9087-17a8deed6db8")}catch{}})();var uC=new Set(["none","null"]);function ti(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function Ye(e){return e===void 0?!1:uC.has(e.trim().toLowerCase())}function ni(e,t,n){if(!Ye(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Oe(e,t,n){if(!e||e.length===0||!e.some(o=>Ye(o)))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ri(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(o.some(a=>Ye(a))){if(o.filter(a=>!Ye(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var fC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function yg(e,t,n,r){if(fC.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Ho("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b968be78-8489-5735-8f95-8e38a36e160a")}catch{}})();var vt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],_C=new Set(vt);function wg(e){return da(e,vt)}function oi(e,t){let n={},r=[];for(let[o,a]of Object.entries(e)){let i=o.toLowerCase();if(!_C.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[i]=a}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:o,...a}=n;return{...a,command:a.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dd87416a-25ec-5dfe-8c54-ef7f43529ecc")}catch{}})();var ln=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Sr,yf,"FORCE_COLOR"]),si=/^[A-Za-z_][A-Za-z0-9_]*$/,cn=["schema","tracker","auto","none"],vg=["source","isolated","snapshot"];function Fr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let a=o.indexOf("=");if(a<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1);if(!si.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(ln.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=s}return Object.keys(r).length>0?r:void 0}function Mr(e,t){if(!e)return;let n=Un(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!si.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(ln.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function ci(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function li(e,t){if(!e)return;let n=e.trim().toLowerCase();if(cn.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${cn.join(", ")}`,d.USAGE)}function dn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(vg.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${vg.join(", ")}`,d.USAGE)}function mn(e){if(!e)return;let t=Un(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Vn(e,t,n){let r=mn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(a){throw new l(`${t} ${n} includes invalid regex "${o}": ${a instanceof Error?a.message:String(a)}`,d.USAGE)}return r}}function di(e,t){if(!e)return;let n=ue(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function mi(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let a=o.indexOf("=");if(a<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1).trim();if(i.length===0||s.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[i]=s}return Object.keys(r).length>0?r:void 0}function pi(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let a=o.indexOf("=");if(a<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1).trim();if(i.length===0||s.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(s);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,d.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var hC=new Set(vt);function ui(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gC(e,t){let n={},r=[];for(let[o,a]of Object.entries(e)){let i=o.toLowerCase();if(!hC.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=a}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`);return n}function sn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function ai(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let a=o.filter(i=>i.length>0);return a.length>0?a:void 0}function bg(e,t,n){let r=ai(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(a){throw n(`field "${t}" includes invalid regex "${o}": ${a instanceof Error?a.message:String(a)}`)}return r}}function ii(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function yC(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:ii(n,"timeout_seconds",t),a=r===void 0?void 0:ii(r,"timeout",t);if(o!==void 0&&a!==void 0&&o!==a)throw t("timeout and timeout_seconds must match when both are provided");let i=o??a;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function wC(e,t){let n=sn(e,"scope",t);if(n===void 0)return"project";if(!ct.includes(n))throw t(`field "scope" must be one of: ${ct.join(", ")}`);return n}function vC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ui(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,a]of Object.entries(n)){if(typeof a!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!si.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(ln.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=a}return Object.keys(r).length>0?r:void 0}function bC(e,t){let n=ai(e,"env_clear",t);if(n){for(let r of n){if(!si.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(ln.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function kC(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function SC(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=ii(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function EC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ui(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,a]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(a)}return Object.keys(r).length>0?r:void 0}function AC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ui(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,a]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=ii(a,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function TC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!ui(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${vt.join(", ")}.`);let o=gC(e,r),a=sn(o,"command",r),i=sn(o,"cmd",r);if(a!==void 0&&i!==void 0&&a!==i)throw r("command and cmd must match when both are provided");let s=a??i;if(s===void 0||s.trim().length===0)throw r('requires a non-empty "command" string');let c=sn(o,"path",r),m=sn(o,"pm_context_mode",r);if(m!==void 0&&!cn.includes(m))throw r(`field "pm_context_mode" must be one of: ${cn.join(", ")}`);let p=dn(sn(o,"workspace_context_mode",r),`${n} ${t}`),u=sn(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:wC(o,r),timeout_seconds:yC(o,r),pm_context_mode:m,workspace_context_mode:p,env_set:vC(o,r),env_clear:bC(o,r),shared_host_safe:kC(o,"shared_host_safe",r),assert_stdout_contains:ai(o,"assert_stdout_contains",r),assert_stdout_regex:bg(o,"assert_stdout_regex",r),assert_stderr_contains:ai(o,"assert_stderr_contains",r),assert_stderr_regex:bg(o,"assert_stderr_regex",r),assert_stdout_min_lines:SC(o,r),assert_json_field_equals:EC(o,r),assert_json_field_gte:AC(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function kg(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(a){throw new l(`${t} value is not valid JSON: ${a instanceof Error?a.message:String(a)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((a,i)=>TC(a,o.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1ffee31a-c272-5494-a04a-01a17b78dd2d")}catch{}})();var Yc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Jc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Sg=[...Yc,...Jc],fi=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function _i(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(Ye(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let a=e.resolveDefinition(o);if(!a)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(a.metadataKey),n.add(a.optionKey)}return{metadataKeys:t,optionKeys:n}}function hi(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let a of o){if(a.allow_unset===!1)continue;let i=new Set;if(typeof a.key=="string"&&a.key.length>0&&i.add(a.key.toLowerCase()),typeof a.metadata_key=="string"&&a.metadata_key.length>0&&i.add(a.metadata_key.toLowerCase()),typeof a.cli_flag=="string"&&a.cli_flag.length>0&&(i.add(a.cli_flag.replaceAll("-","_").toLowerCase()),i.add(a.cli_flag.toLowerCase())),Array.isArray(a.cli_aliases))for(let s of a.cli_aliases)typeof s!="string"||s.length===0||(i.add(s.replaceAll("-","_").toLowerCase()),i.add(s.toLowerCase()));if(i.has(r))return{optionKey:a.key,metadataKey:a.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Ag(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Xc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function xe(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var Tg=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function CC(e,t){return t==="defined"?e!==void 0:!!e}function Eg(e,t,n){if(!CC(e,n))return;let r=ue(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function IC(e,t,n){let r=e?ie(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function RC(e){return Array.from(new Set(Xc(e).map(t=>xe(t.toLowerCase(),Hd,"event weekday")))).sort((t,n)=>ds(t)-ds(n))}function OC(e){return Array.from(new Set(Xc(e).map(t=>{let n=ue(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function xC(e,t){return Array.from(new Set(Xc(e).map(n=>ie(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Cg(e,t,n,r){let o=e.recur_freq?.trim(),a=e.recur_interval?.trim(),i=e.recur_count?.trim(),s=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),p=e.recur_exdates?.trim();if(![o,a,i,s,c,m,p].some(b=>b!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let u=xe(o.toLowerCase(),zd,"event recurrence frequency"),f=Eg(a,"recur_interval",r),_=Eg(i,"recur_count",r),h=IC(s,t,n),y=RC(c),g=OC(m),w=xC(p,n);return{freq:u,interval:f,count:_,until:h,by_weekday:y.length>0?y:void 0,by_month_day:g.length>0?g:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2c9f586-3e93-5caf-a5c2-38be30c67171")}catch{}})();function Dr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Ur(e,t,n=Mt()){for(let r of t??[])try{Yd(e,r.id,r.kind,n)}catch(o){throw new l(An(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Ig(e,t){return(await se(e,{schema:t})).document.metadata.created_at}async function PC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Ig(n,t.schema)}function NC(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function LC(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:a})=>a===null?[]:[[o,a]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await Ig(n.get(o),e.context.schema)])));for(let o of e.holders){let a=await PC(o,e.context);if(a!==void 0)for(let i of t){let s=r.get(i.id),c=Date.parse(a),m=Date.parse(s);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw NC({holder:o,dependency:i,sourceCreatedAt:a,targetCreatedAt:s,registry:e.registry})}}}async function pn(e){let t=e.registry??Mt(),n=(e.dependencies??[]).filter(i=>!Qp(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await q(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),a=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,s)=>i<s?-1:1);if(a.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${a.length===1?"":"s"} not found: ${a.join(", ")}`,d.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:a,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${a.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:a,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${a[0]}" --limit 10`}});return await LC({dependencies:n,missingTargets:a,resolutions:o,holders:e.holders??[],registry:t,context:e}),a.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var $C={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function FC(e){return $C[e]}function Qc(e){return FC(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Rg="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",MC="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",DC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,UC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,xg=1e3,Zc=60*xg,GC=60*Zc;function Og(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function jC(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new l(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,d.USAGE);let o=r.replace(/^([+-]?\d+)mo$/i,"$1m"),a=DC.exec(r);if(a){let c=a[1]==="-"?-1:1,m=Number.parseInt(a[2],10)*c;return Og(n.getTime()+m*Zc,r)}let i=UC.exec(r);if(i){let[,c,m,p,u]=i;if(m||p||u){let f=c==="-"?-1:1,_=Number.parseInt(m??"0",10),h=Number.parseInt(p??"0",10),y=Number.parseInt(u??"0",10),g=_*GC+h*Zc+y*xg;return Og(n.getTime()+f*g,r)}}let s=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return ie(s,n,"event.duration")}function Pg(e,t,n,r){if(t&&n)throw new l(MC,d.USAGE);if(n){let a=jC(e,n);if(a<e)throw new l(Rg,d.USAGE);return a===e?void 0:a}if(!t)return;let o=ie(t,r,"event.end");if(o<e)throw new l(Rg,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var qC=["at","date","text","title"],KC=["start","date","end","duration","title","description","location","timezone","all_day",...Tg],zC=["key","value"];function Ng(e,t){return t==="trimmed"?e?.trim():e}function HC(e,t){return t==="defined"?e!==void 0:!!e}function gi(e,t,n){return e.map(r=>{let o=de(r,"--reminder");We(o,"--reminder",qC);let a=Ng(o.at??o.date,n.valueMode),i=Ng(o.text??o.title,n.valueMode);if(!a||!i)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let s=i.trim();if(!s)throw new l("--reminder text must not be empty",d.USAGE);return{at:ie(a,t,"reminder.at"),text:s}})}function yi(e,t,n){return e.map(r=>{let o=de(r,"--event");We(o,"--event",KC);let a=(o.start??o.date)?.trim();if(!a)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=ie(a,t,"event.start"),s=o.end?.trim(),c=o.duration?.trim(),m=Pg(i,s,c,t),p=o.title,u=o.description,f=o.location,_=o.timezone,h=p?.trim(),y=u?.trim(),g=f?.trim(),w=_?.trim(),b=[["title",p,h],["description",u,y],["location",f,g],["timezone",_,w]];for(let[P,M,z]of b)if(M!==void 0&&!z)throw new l(`--event ${P} must not be empty`,d.USAGE);let S=o.all_day?.trim(),T=Cg(o,i,t,n.recurrenceEmptyNumericGuard),L=HC(S,n.allDayEmptyGuard)?Ag(S,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:L,timezone:w,recurrence:T}})}function wi(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let o,a;if(r.includes(",")||r.includes(`
21
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let i=de(r,"--type-option");We(i,"--type-option",zC),o=i.key?.trim(),a=i.value?.trim()}else{let i=r.indexOf("="),s=r.indexOf(":"),c=i;if(i<=0&&s>0&&(c=s),c<=0||c===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,c).trim(),a=r.slice(c+1).trim()}if(!o||!a)throw new l("--type-option requires key and value",d.USAGE);t[o]=a}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b72dfe53-b429-5722-aaf3-bc6bbf099d3e")}catch{}})();var BC=["strict","progressive"],VC=["lightweight"],Mg=new Set(["Reminder","Meeting","Event"]),WC=new Set(["author","created_at","text"]),tl=[...Sg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...fi],YC=(()=>{let e=new Map;for(let t of tl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),vi=new Map(tl.map(e=>[e.optionKey,e.canonical])),JC=tl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function XC(e,t){let n=te(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function QC(e,t){let n=e.default_status;if(n!==void 0){let r=te(n,t);if(r)return r}return t.open_status}function el(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var ZC=ti();function Dg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let a=t.unset?[...t.unset]:[];a.includes(o)||a.push(o),t.unset=a};Ye(t.template)&&(t.template=void 0);let r=new Set([...vi.keys(),"rank"]);for(let o of r){let a=t[o];if(typeof a!="string"||!Ye(a))continue;let i=o==="rank"?"order":vi.get(o)??o;n(i),t[o]=void 0}return Ie(e,ri(t,ZC))}function we(e){if(e!==void 0)return e}function e0(e,t){return _i({raw:e,supportedFields:JC,resolveDefinition:n=>YC.get(n)??hi(n,"create",t)})}var Lg=["id","kind","type","author","created_at","source_kind"],bi=["path","scope","note"];function t0(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let a=o.trim(),i=ki(a,Lg);Dr(a,i);let s=i?de(o,"--dep"):{id:a,kind:"related"};i&&We(s,"--dep",Lg);let c=we(s.id),m=n0(we(s.kind??s.type));if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(c.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=vr(we(s.source_kind)),u=we(s.author);return{id:br(c,n,p),kind:xe(m,Vt,"dependency kind","kind"),created_at:el(s.created_at,t),author:u??r,source_kind:p??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function n0(e){return typeof e=="string"?mo(e)??e.trim():e}function ki(e,t){return da(e,t)?!0:ua(e)}function fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Oe(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let a=o.trim(),i=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},s;try{s=de(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return i();throw m}if(Object.keys(s).filter(m=>!WC.has(m)).length>0)return{created_at:el(s.created_at,n),author:we(s.author)??r,text:a};let c=s.text??"";if(c==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:el(s.created_at,n),author:we(s.author)??r,text:c}}),explicitEmpty:!1})}function nl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=ki(n,bi);Js(n,"--file","file path",r);let o=r?de(t,"--file"):{path:n};if(r&&We(o,"--file",bi),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:xe(o.scope??"project",ct,"file scope"),note:we(o.note)}}),explicitEmpty:!1})}function rl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=ki(n,vt);Js(n,"--test","test command",r);let o=r?oi(de(t,"--test"),"--test"):{command:n},a=we(o.command),i=we(o.path);if(!a)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let s=we(o.timeout_seconds),c=we(o.timeout);if(s&&c&&s!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=s??c;return{command:a,path:i,scope:xe(o.scope??"project",ct,"test scope"),timeout_seconds:m?ue(m,"timeout_seconds"):void 0,pm_context_mode:li(o.pm_context_mode,"--test"),workspace_context_mode:dn(o.workspace_context_mode,"--test"),env_set:Fr(o.env_set,"--test"),env_clear:Mr(o.env_clear,"--test"),shared_host_safe:ci(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:mn(o.assert_stdout_contains),assert_stdout_regex:Vn(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:mn(o.assert_stderr_contains),assert_stderr_regex:Vn(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:di(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:mi(o.assert_json_field_equals,"--test"),assert_json_field_gte:pi(o.assert_json_field_gte,"--test"),note:we(o.note)}}),explicitEmpty:!1})}function ol(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=ki(n,bi),o=r?de(t,"--doc"):{path:n};if(r&&We(o,"--doc",bi),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:xe(o.scope??"project",ct,"doc scope"),note:we(o.note)}}),explicitEmpty:!1})}function r0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:gi(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function o0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--event","Use --clear-events to clear linked events."),{values:yi(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function a0(e,t,n,r=[]){let o=[...so.filter(a=>e[a]!==void 0),...r.filter(a=>e[a]!==void 0),...t.length>0?["body"]:[],...n.map(a=>`unset:${a}`)];return Array.from(new Set(o))}function i0(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function $g(e,t,n){let r=nr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function s0(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Ug(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function c0(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add($g(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add($g(r,e.name,"required_create_repeatables"));return n}function l0(e,t,n,r){for(let o of e)if(!(!Ug(t,o)&&!n.has(o)))throw new l(`Option ${Ae("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function d0(e,t,n){if(t!=="strict")return;let r=e.filter(a=>n.has(a)&&!Qc(a));if(r.length===0)return;let o=[...new Set(r.map(a=>Ae("create",a)))].sort((a,i)=>a.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function m0(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:wi(e),explicitEmpty:!1})}async function p0(e){return await fa(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function u0(e){return ft(e)?await p0(e):e}function f0(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${BC.join(", ")}`,d.USAGE)}function _0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${VC.join(", ")}`,d.USAGE)}function h0(e,t,n){let r=f0(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function g0(e,t,n,r){let o=e.name,a=s0(t),i=c0(e,n),s=Tn(e,"create",i);if(s.errors.length>0)throw new l(s.errors.join("; "),d.CONFLICT);l0(s.disabled,a,r,o),d0(s.required,n,r);let c=p=>p==="status"&&e.default_status!==void 0||r.has(p)&&Qc(p)?!0:Ug(a,p),m=s.required.filter(p=>!c(p));return[...new Set(m.map(p=>Ae("create",p)))].sort((p,u)=>p.localeCompare(u))}var Gg=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function y0(e,t){let n=[];for(let r of e){let o=r.match(Gg);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function w0(e,t){return e.filter(n=>{let r=n.match(Gg);return!r||r[2]!==t})}function v0(e,t,n,r){let o=w0(e,t);if(o.length===0)return;let a=jg(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[a],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function b0(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function k0(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function jg(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],a=["--status","--priority","--message"],i=[...new Set([...a,...t])],s=new Set(["--title","--description","--type"]);for(let c of i)s.has(c)||(o.push(...k0(c,e.name,r)),s.add(c));for(let c of n){let m=b0(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function al(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function S0(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function E0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function A0(){let e=O();return e?e.commands.some(t=>t.action==="templates-show"||E0(t.command)==="templates show"):!1}function T0(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[o,a]of Object.entries(n)){if(typeof a=="string"||typeof a=="number"||typeof a=="boolean"){r[o]=a;continue}if(Array.isArray(a)&&a.every(i=>typeof i=="string")){r[o]=[...a];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function C0(e,t,n){if(!A0())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Yo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return T0(r.result,e)}function V(e,t,n){return e.has(t)||n===void 0?void 0:we(n)}function un(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var I0=new Set(["milestone","meeting","reminder","event"]);function qg(e,t,n,r){let o=t!==void 0,a=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return I0.has(e.toLowerCase())&&!o&&!a&&!i}function R0(e,t,n,r,o){let a=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&a.push(`event_without_schedule:${t}:no_time_set`),qg(e,n,r,o)&&a.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),a}async function O0(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await na(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function x0(e,t,n,r,o,a){let i=Ea(ya(o),t.id_prefix);if(Qo(i))return{parent:i,warnings:[]};if(va(r,i,t.id_prefix),await q(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let s=Ke(i,t.id_prefix);return{parent:i,warnings:wa(s,a).warnings}}async function P0(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await x0(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function N0(e){if(e.explicitId===void 0)return hr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||Hu(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=Ke(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Fg(e,t,n,r,o){let a=V(e,t,n);if(a===void 0)return{value:void 0,warnings:[]};let i=ba(r,a,o);return{value:i.value,warnings:i.warnings}}async function L0(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:a,status:i,statusExplicit:s,nowValue:c,author:m}=e,p=e.dependencyValues;if(a===void 0)return{dependencyValues:p,status:i};let u=Ke(a,n.id_prefix),f=await q(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:p,status:i};if((p??[]).some(h=>h.id===f.id&&h.kind==="blocked_by")||(p=[...p??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),s)return{dependencyValues:p,status:i};let _=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((h,y)=>h.localeCompare(y))[0]??o.open_status;return{dependencyValues:p,status:_}}function $0(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&be(r,n)){e.type=r;return}be("Task",n)&&(e.type="Task")}function F0(e,t){return e.options.filter(n=>nr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function M0(e,t,n,r,o){let a=e,i=[];if(a.template!==void 0){let h=a.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await C0(h,t,n);a=Dg(S0(y,a))}if(a.type===void 0&&$0(a,r,o),a.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let s=be(a.type,o);if(!s){let h=Vu(a.type),y=h?be(h,o):void 0;if(y)i.push(`type_coercion:${a.type.trim()}:${y}`),a.type=y,s=y;else throw new l(Rt(a.type,o.types,Ot(n,r.schema)),d.USAGE)}let c=po(s,o);if(!c)throw new l(`Invalid type value "${a.type}"`,d.USAGE);let m=c.name,p=F0(c,a),u=p.map(h=>`${h.key}=${String(a[h.key])}`);if(u.length>0){a.typeOption=[...u,...a.typeOption??[]];for(let h of p)delete a[h.key]}let f=_0(a.schedulePreset);if(f!==void 0&&!Mg.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=h0(a.createMode,f,r.governance.create_mode_default);return{resolvedOptions:a,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function D0(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let a of o)if(a.enabled){if(a.values&&a.values.length>0)throw new l(`Cannot combine ${a.clearFlag} with ${a.valueFlag}`,d.USAGE);n.add(a.metadataKey),r.add(a.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function U0(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let a=vi.get(r)??r;throw new l(`Cannot combine --unset ${a} with ${Ae("create",r)}`,d.USAGE)}}function G0(e){let t=(n,r)=>{let o=vi.get(r),a=o?`Use --unset ${o} to clear this field.`:void 0;ni(n,Ae("create",r),a)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function j0(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}var q0={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function K0(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:a,type:i,createMode:s,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let y=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${y}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),p=[jg(n,r,o,a),...m.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+i+").")];s==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Mg.has(i)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&u.push(`Required custom field formats: ${m.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let y=h.split(" ",1)[0],g=q0[y];return g?[g]:[]}))];f.length>0&&u.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${i} ${h} ...`),p],nextSteps:u,recovery:s==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function z0(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Pt(t.tags):[];return Ln(n,t.addTags)}function H0(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=un(e,"order",n,o=>ue(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function B0(e,t,n,r,o,a){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?a:ie(r.completedAt,new Date(a),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let s=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:zc(s,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function V0(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:a,author:i,extensionFieldNames:s,afterDocument:c,beforeDocument:m,historyMessage:p,changedFields:u,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=dt(t,n,r,o.item_format,a.type_to_folder),g=tt(t,r),w=Mt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(P=>w.resolve(P.kind)?.hierarchy),S=await Ja({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,L=[];try{let P=await Te(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let M=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await fe(t,o.item_format,a.type_to_folder,void 0,o.schema):void 0;if(await q(t,r,o.id_prefix,o.item_format,a.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if(M){let ee=$(o.schema);Aa(M,[...M,c.metadata],r,Ee=>oe(Ee,ee),w)}let z=await yr({pmRoot:t,settings:o,operation:"create",author:i,before:null,after:c});await Wo({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:ka({pmRoot:t,settings:o,typeToFolder:a.type_to_folder})});let H=await $t(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),J=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await qn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await ne(y,Be(c,{format:o.item_format,schema:o.schema,extensionFieldNames:s}));try{let ee=$e({nowIso:f,author:i,op:"create",before:m,after:c,message:p,context:z.decisions.length===0?void 0:{workflow_policies:z.decisions}});await xt(g,ee)}catch(ee){throw await En(y),ee}T&&(await S(),T=!1),J=await Ft({pmRoot:t,preferredFormat:o.item_format,typeToFolder:a.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await H()}L=[...z.warnings,...M?Ga(M,[...M,c.metadata],r):[],...J,...await Y({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u}),...await Y({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u})],In({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Qt(c.metadata,u),changed_fields:u})}finally{await P()}}finally{T&&await S()}return L}async function Gt(e,t){let n=Dg(await u0(e)),r=E(process.cwd(),t.path);await I(r);let o=await A(r),a=$(o.schema),i=nt(o.schema),s=x(o,O()),c=await M0(n,t,r,o,s);n=c.resolvedOptions;let{typeDefinition:m,type:p,createMode:u}=c,f=e0(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=D0(n,f);U0(n,f),G0(n);let y=g0(m,n,u,h),g=k(),w=C(we(n.author),o.author_default),b=t0(n.dep,g,o.id_prefix,w),S=fn("--comment",n.comment,g,w),T=fn("--note",n.note,g,w),L=fn("--learning",n.learning,g,w),P=nl(n.file),M=rl(n.test);M.values=await zn(M.values,w,g);let z=ol(n.doc),H=r0(n.reminder,g),J=o0(n.event,g),ee=m0(n.typeOption),Ee=rr(p,ee.values,s),Qe=O(),G=Tt(Qe),pe=co(n.field,Qe),Ze=gu(n,i,p),Zi=new Set(Ze.missing_required_flags),es=i.definitions.filter(W=>Zi.has(`--${W.cli_flag}`));j0(pe,Ze,f);let tr=y0(Ee.errors,p),zt=tr.map(W=>`--type-option ${W}=<value>`),Zr=[...new Set([...y,...zt,...Ze.missing_required_flags])].sort((W,cs)=>W.localeCompare(cs));K0({combinedMissingFlags:Zr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:tr,openStatus:a.open_status,type:p,createMode:u,missingRequiredRuntimeFields:es}),v0(Ee.errors,p,m,a);let qe=await N0({pmRoot:r,settings:o,typeRegistry:s,explicitId:n.id}),St=n.status!==void 0?XC(n.status,a):QC(m,a),eo=n.priority!==void 0?Fn(n.priority):2,R=f.metadataKeys,Ht=z0(R,n),bn=un(R,"deadline",n.deadline,W=>ie(W,new Date(g),"deadline")),Et=un(R,"estimated_minutes",n.estimatedMinutes,W=>$n(W,"estimated-minutes")),ts=V(R,"acceptance_criteria",n.acceptanceCriteria),et=V(R,"definition_of_ready",n.definitionOfReady),ns=H0(R,n),to=V(R,"goal",n.goal),pb=V(R,"objective",n.objective),ub=V(R,"value",n.value),fb=V(R,"impact",n.impact),_b=V(R,"outcome",n.outcome),hb=V(R,"why_now",n.whyNow),gb=V(R,"assignee",n.assignee),yb=R.has("author")?void 0:we(n.author)??w,wb=V(R,"parent",n.parent),Cd=await O0(wb,n,R,r),rs=Cd.parent,vb=Cd.parentSource,bb=V(R,"reviewer",n.reviewer),kb=un(R,"risk",n.risk,W=>xe(Xa(W),kn,"risk")),Sb=un(R,"confidence",n.confidence,W=>Za(W)),Eb=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Id=o.validation.sprint_release_format,Bt=[...c.warnings,...R0(p,qe,bn,H.values,J.values)],Rd=await P0({itemId:qe,parent:rs,pmRoot:r,settings:o,typeRegistry:s,policy:Eb});rs=Rd.parent,Bt.push(...Rd.warnings);let Od=Fg(R,"sprint",n.sprint,"sprint",Id),Ab=Od.value;Bt.push(...Od.warnings);let xd=Fg(R,"release",n.release,"release",Id),Tb=xd.value;Bt.push(...xd.warnings);let Pd=V(R,"blocked_by",n.blockedBy),Nd=await L0({pmRoot:r,settings:o,typeRegistry:s,statusRegistry:a,blockedBy:Pd,dependencyValues:b.values,status:St,statusExplicit:n.status!==void 0,nowValue:g,author:w}),os=Nd.dependencyValues;Ur(qe,os),Bt.push(...await pn({pmRoot:r,dependencies:os,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:s.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:qe,createdAt:g}],schema:o.schema})),St=Nd.status;let Cb=V(R,"blocked_reason",n.blockedReason),Ib=V(R,"unblock_note",n.unblockNote),Rb=V(R,"reporter",n.reporter),Ob=un(R,"severity",n.severity,W=>xe(Qa(W),Sn,"severity")),xb=V(R,"environment",n.environment),Pb=V(R,"repro_steps",n.reproSteps),Ld=V(R,"resolution",n.resolution),Nb=V(R,"expected_result",n.expectedResult),Lb=V(R,"actual_result",n.actualResult),$b=V(R,"affected_version",n.affectedVersion),Fb=V(R,"fixed_version",n.fixedVersion),Mb=V(R,"component",n.component),Db=un(R,"regression",n.regression,W=>ei(W)),Ub=V(R,"customer_impact",n.customerImpact),as=al(n.title,"--title"),is=n.description??"",no=n.body??"",$d=await qn({title:as,description:is,body:no},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Bt.push(...Pa($d));let ss=B0(St,a,o,n,Ld,g),Gb=ss.closeReason,jb=St===a.close_status?g:void 0,qb=ss.completedAt;Bt.push(...ss.warnings);let ro=qs({id:qe,title:as,description:is,type:p,type_options:Ee.normalized,status:St,closed_at:jb,completed_at:qb,close_reason:Gb,priority:eo,tags:Ht,created_at:g,updated_at:g,deadline:bn,assignee:gb,author:yb,estimated_minutes:Et,acceptance_criteria:ts,definition_of_ready:et,order:ns,goal:to,objective:pb,value:ub,impact:fb,outcome:_b,why_now:hb,parent:rs,reviewer:bb,risk:kb,confidence:Sb,sprint:Ab,release:Tb,blocked_by:Pd,blocked_reason:Cb,unblock_note:Ib,reporter:Rb,severity:Ob,environment:xb,repro_steps:Pb,resolution:Ld,expected_result:Nb,actual_result:Lb,affected_version:$b,fixed_version:Fb,component:Mb,regression:Db,customer_impact:Ub,dependencies:os,comments:S.values,notes:T.values,learnings:L.values,files:P.values,tests:M.values,docs:z.values,reminders:H.values,events:J.values,...pe,...Ze.values});try{lo(ro,Qe)}catch(W){throw new l(W instanceof Error?W.message:"Invalid extension item field values",d.USAGE)}let Kb=rt({metadata:ro,body:no},{schema:o.schema,extensionFieldNames:G}),zb={metadata:{},body:""},Fd=[..._].sort((W,cs)=>W.localeCompare(cs)),Hb=i0(n.message,Fd),Md=a0(ro,no,Fd,[...Object.keys(pe),...Object.keys(Ze.values??{})]),Bb=await V0({pmRoot:r,type:p,id:qe,settings:o,typeRegistry:s,author:w,extensionFieldNames:G,afterDocument:Kb,beforeDocument:zb,historyMessage:Hb,changedFields:Md,nowValue:g,similarityCandidate:{title:as,description:is,body:no},allowDuplicate:n.allowDuplicate}),Dd=structuredClone(ro);u==="strict"&&_.has("dependencies")&&(Dd.dependencies=[]);let Vb=yg(qe,p,St,a);return qg(p,bn,H.values,J.values)&&Xp(`[pm] warning: ${p} '${qe}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${qe} --deadline <ISO>' or 'pm update ${qe} --event "start=<ISO>,end=<ISO>"'.`),{item:Dd,changed_fields:Md,warnings:[...Bt,...Bb],...Object.fromEntries([["parent_source",vb],["next_transition",Vb],["similarity_advisory",$d]].filter(W=>W[1]!==void 0))}}import Si from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d29ab3a3-319f-506f-8289-78d786b95255")}catch{}})();async function il(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),a=C(t.author,o.author_default),i=await ef({pmRoot:r,settings:o,id:e,author:a,message:t.message,force:t.force,dryRun:t.dryRun}),s=i.targetPath?Si.relative(r,i.targetPath).split(Si.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...s?{target_path:s}:{},history_retained:Si.relative(r,tt(r,i.item.id)).split(Si.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7047beb-5c3a-5d97-acb9-7ddd15a223ec")}catch{}})();async function W0(e){await I(e)}async function sl(e,t,n){let r=E(process.cwd(),n.path);if(await W0(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),u=Pn(C(void 0,p.author_default));return await hu(r),await ja({pmRoot:r,settings:p,principal:u}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await na(r);if(p===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 u=await Y0(r,p);return{action:"show",focused_item:p,title:u,message:`Focused on ${p}${u?` (${u})`:""}. New items default --parent to it.`}}let o=await A(r),a=x(o,O()),i=await q(r,e,o.id_prefix,o.item_format,a.type_to_folder);if(!i)throw await _t(r,e,o.id_prefix,a.type_to_folder);let s=Ke(i.id,o.id_prefix),c=await se(i,{schema:o.schema}),m=Kg(c.document.metadata.title);return await _u(r,s),await ja({pmRoot:r,settings:o,principal:Pn(C(void 0,o.author_default)),itemId:s}),{action:"set",focused_item:s,title:m,message:`Focused on ${s}${m?` (${m})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function Y0(e,t){let n=await A(e),r=x(n,O()),o=await q(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let a=await se(o,{schema:n.schema});return Kg(a.document.metadata.title)}function Kg(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Ei(e){return Ho("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ee587b5-5aa8-5d10-89d7-acc4a5edb53f")}catch{}})();var ml=[...Yc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Jc,...fi],J0=(()=>{let e=new Map;for(let t of ml)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Ai=new Map(ml.map(e=>[e.optionKey,e.canonical])),X0=ml.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),Q0=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),Z0=ti({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Xg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let a=t.unset?[...t.unset]:[];a.includes(o)||a.push(o),t.unset=a},r=new Set([...Ai.keys(),"rank"]);for(let o of r){let a=t[o];if(typeof a!="string"||!Ye(a))continue;let i=o==="rank"?"order":Ai.get(o)??o;n(i),t[o]=void 0}return Ie(e,ri(t,Z0))}function Qg(e,t,n=[]){return _i({raw:e,supportedFields:X0,resolveDefinition:r=>{let o=n.find(a=>{let i=a.toLowerCase();return i===r||i.replaceAll("_","-")===r||i.replaceAll("-","_")===r});return J0.get(r)??hi(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var zg=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Hg(e){let t=e.disallowedFlags.flatMap(r=>{let o=zg.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=zg.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function eI(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let a=(c,m,p)=>{c&&p.push(m)};if(o){let c=[];if(a(t.title!==void 0,"--title",c),a(t.description!==void 0,"--description",c),a(t.body!==void 0,"--body",c),a(t.status!==void 0,"--status",c),a(t.closeReason!==void 0,"--close-reason",c),a(t.priority!==void 0,"--priority",c),a(t.type!==void 0,"--type",c),a(t.tags!==void 0,"--tags",c),a(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),a(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),a(t.deadline!==void 0,"--deadline",c),a(t.estimatedMinutes!==void 0,"--estimate",c),a(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),a(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),a(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),a(t.definitionOfReady!==void 0,"--definition-of-ready",c),a(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),a(t.goal!==void 0,"--goal",c),a(t.objective!==void 0,"--objective",c),a(t.value!==void 0,"--value",c),a(t.impact!==void 0,"--impact",c),a(t.outcome!==void 0,"--outcome",c),a(t.whyNow!==void 0,"--why-now",c),a(t.assignee!==void 0,"--assignee",c),a(t.parent!==void 0,"--parent",c),a(t.reviewer!==void 0,"--reviewer",c),a(t.risk!==void 0,"--risk",c),a(t.confidence!==void 0,"--confidence",c),a(t.sprint!==void 0,"--sprint",c),a(t.release!==void 0,"--release",c),a(t.blockedBy!==void 0,"--blocked-by",c),a(t.blockedReason!==void 0,"--blocked-reason",c),a(t.unblockNote!==void 0,"--unblock-note",c),a(t.reporter!==void 0,"--reporter",c),a(t.severity!==void 0,"--severity",c),a(t.environment!==void 0,"--environment",c),a(t.reproSteps!==void 0,"--repro-steps",c),a(t.resolution!==void 0,"--resolution",c),a(t.expectedResult!==void 0,"--expected-result",c),a(t.actualResult!==void 0,"--actual-result",c),a(t.affectedVersion!==void 0,"--affected-version",c),a(t.fixedVersion!==void 0,"--fixed-version",c),a(t.component!==void 0,"--component",c),a(t.regression!==void 0,"--regression",c),a(t.customerImpact!==void 0,"--customer-impact",c),a(t.depRemove!==void 0,"--dep-remove",c),a(t.replaceDeps===!0,"--replace-deps",c),a(t.replaceTests===!0,"--replace-tests",c),a(t.replaceFiles===!0,"--replace-files",c),a(t.replaceDocs===!0,"--replace-docs",c),a(t.comment!==void 0,"--comment",c),a(t.note!==void 0,"--note",c),a(t.learning!==void 0,"--learning",c),a(t.file!==void 0,"--file",c),a(t.test!==void 0,"--test",c),a(t.doc!==void 0,"--doc",c),a(t.reminder!==void 0,"--reminder",c),a(t.event!==void 0,"--event",c),a(t.typeOption!==void 0,"--type-option",c),a(t.clearDeps===!0,"--clear-deps",c),a(t.clearComments===!0,"--clear-comments",c),a(t.clearNotes===!0,"--clear-notes",c),a(t.clearLearnings===!0,"--clear-learnings",c),a(t.clearFiles===!0,"--clear-files",c),a(t.clearTests===!0,"--clear-tests",c),a(t.clearDocs===!0,"--clear-docs",c),a(t.clearReminders===!0,"--clear-reminders",c),a(t.clearEvents===!0,"--clear-events",c),a(t.clearTypeOptions===!0,"--clear-type-options",c),a(t.force===!0,"--force",c),a(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw Hg({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];a(t.status!==void 0,"--status",i),a(t.closeReason!==void 0,"--close-reason",i),a(t.assignee!==void 0,"--assignee",i),a(t.parent!==void 0,"--parent",i),a(t.blockedBy!==void 0,"--blocked-by",i),a(t.blockedReason!==void 0,"--blocked-reason",i),a(t.unblockNote!==void 0,"--unblock-note",i),a(t.dep!==void 0,"--dep",i),a(t.depRemove!==void 0,"--dep-remove",i),a(t.replaceDeps===!0,"--replace-deps",i),a(t.replaceTests===!0,"--replace-tests",i),a(t.replaceFiles===!0,"--replace-files",i),a(t.replaceDocs===!0,"--replace-docs",i),a(t.note!==void 0,"--note",i),a(t.learning!==void 0,"--learning",i),a(t.test!==void 0,"--test",i),a(t.reminder!==void 0,"--reminder",i),a(t.event!==void 0,"--event",i),a(t.clearDeps===!0,"--clear-deps",i),a(t.clearComments===!0,"--clear-comments",i),a(t.clearNotes===!0,"--clear-notes",i),a(t.clearLearnings===!0,"--clear-learnings",i),a(t.clearFiles===!0,"--clear-files",i),a(t.clearTests===!0,"--clear-tests",i),a(t.clearDocs===!0,"--clear-docs",i),a(t.clearReminders===!0,"--clear-reminders",i),a(t.clearEvents===!0,"--clear-events",i);let s=[...n].filter(c=>Q0.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...s),i.length>0)throw Hg({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${i.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:i})}function tI(e,t){let n=te(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function nI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Ip({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=te(e.fromStatus,e.statusRegistry)??e.fromStatus,r=te(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Rp(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function rI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Zg(e)}function Zg(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Wn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var oI=["id","kind","type","author","created_at","source_kind"],aI=["id","kind","type","author","created_at","source_kind"];function ey(e){return e.startsWith("```")||e.includes(`
22
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:ua(e)}function ty(e){return typeof e=="string"?mo(e)??e.trim():e}function Ci(e,t,n,r){return e?(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let a=o.trim(),i=ey(a);Dr(a,i);let s=i?de(o,"--dep"):{id:a,kind:"related"};i&&We(s,"--dep",oI);let c=s.id?.trim(),m=ty((s.kind??s.type)?.trim());if(!c||!m)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(c.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=vr(Wn(s.source_kind)),u=Wn(s.author);return{id:br(c,t,p),kind:xe(m,Vt,"dependency kind","kind"),created_at:rI(s.created_at,n),author:u??r,source_kind:p??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function iI(e,t){return e?(Oe(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);let o=ey(r);if(Dr(r,o,"--dep-remove"),o){let a=de(r,"--dep-remove");We(a,"--dep-remove",aI);let i=a.id?.trim();if(!i)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(i.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${i}"`,d.USAGE);let s=ty(Wn(a.kind??a.type)),c=vr(Wn(a.source_kind)),m=Wn(a.author),p=Wn(a.created_at);return{id:br(i,t,c),kind:s?xe(s,Vt,"dependency kind","kind"):void 0,source_kind:c,author:m,created_at:p?Zg(p):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:Ke(r,t)}})):[]}function Ti(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function sI(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),a=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,a].join("\0")}function cI(e,t,n,r){let o=[...e??[]],a=!1;if(t===void 0){let i=o.filter(s=>s.kind!=="blocked_by");return i.length!==o.length&&(o=i,a=!0),a?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),a=!0),a?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function lI(e,t,n,r,o,a){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let s=await q(n,Ke(i,r),r,o,a);return s?{id:s.id}:{unresolved:i}}function dI(e,t,n,r,o){let a=cI(e.dependencies,t,n,r);a.changed&&(a.dependencies===void 0?delete e.dependencies:e.dependencies=a.dependencies,o.includes("dependencies")||o.push("dependencies"))}function mI(e){return`${e.path}::${e.scope}`}function pI(e){return`${e.path}::${e.scope}`}function uI(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function ny(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Bg(e,t){let n=nr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function fI(e,t,n){let r=new Set,o=(a,i)=>{i&&r.add(a)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let a=Qg(e.unset,t,n);for(let i of a.optionKeys)o(i,!0)}return r}function _I(e,t,n,r,o){let a=po(e,n);if(!a)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=Tn(a,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let s=fI(t,r,o);for(let c of i.disabled)if(s.has(Bg(c,e)))throw new l(`Option ${Ae("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!s.has(Bg(c,e)))throw new l(`Missing required option ${Ae("update",c)} for type "${e}"`,d.USAGE)}var hI=new Set(["order","rank"]),gI=ws.filter(e=>!hI.has(e)),ry=["tags","closeReason",...gI],yI=["title","description","body","status","closeReason","completedAt","priority","type",...ws,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],wI=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ie(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>$n(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],vI=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>xe(Xa(e),kn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Za(e)}],bI=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>xe(Qa(e),Sn,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>ei(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function dl(e,t,n){for(let r of e){let o=t[r.optionKey],a=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!a)){if(a){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${Ae("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function kI(e){return Xg(await fa(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function pl(e){return ft(e)?await kI(e):Xg(e)}function SI(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function cl(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function ul(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);cl({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),cl({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),cl({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function EI(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function AI(e){let t={};for(let n of ry)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function TI(e,t){let n=AI(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let a=Ai.get(r)??r;throw new l(`Cannot combine --unset ${a} with ${Ae("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function CI(e){let t=(n,r)=>{let o=Ai.get(r),a=o?`Use --unset ${o} to clear this field.`:void 0;ni(n,Ae("update",r),a)};for(let n of ry)t(e[n],String(n));t(e.order??e.rank,"order"),Oe(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Oe(e.event,"--event","Use --clear-events to clear linked events.")}function II(e,t){let n={};for(let r of yI)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function RI(e){let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await se(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function OI(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function xI(e){e.before&&Aa(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>oe(t,e.statusRegistry),Mt())}function PI(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function NI(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Ea(ya(e.options.parent),e.settings.id_prefix);if(Qo(t))return{resolvedParentValue:t,warnings:[]};if(va(e.id,t,e.settings.id_prefix),await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=Ke(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:wa(n,e.parentReferencePolicy).warnings}}function LI(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function $I(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await se(t,{schema:e.settings.schema}),r=e.options.type!==void 0?be(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=nI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function FI(e){if(!e.fieldFlags.status||te(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let t=Object.entries(e.fieldFlags).filter(([i,s])=>s&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),n=[],r=[];if(t.length>0){let i=Ie(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),s=await it(e.id,i,e.global);r=s.changed_fields,n.push(...s.warnings)}let o=await wt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),a=[...e.workflowTransitionWarnings,...n,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...r,...o.changed_fields],warnings:a}}function MI(e,t,n,r){return t.title!==void 0&&(e.metadata.title=al(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),te(e.metadata.status,n)??e.metadata.status}var DI=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function UI(e,t){for(let n of DI)e[n]!==void 0&&(delete e[n],t.push(n))}function GI(e,t,n,r,o){let a=tI(n,t.statusRegistry);if(e.metadata.status=a,o.push("status"),a===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!oe(a,t.statusRegistry)&&oe(r,t.statusRegistry)&&UI(e.metadata,o)}function jI(e,t,n,r){if(t.options.status!==void 0&&GI(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!oe(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=ie(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function qI(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&oe(n,t.statusRegistry)&&!oe(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function KI(e,t,n,r){jI(e,t,n,r),qI(e,t,n,r)}function zI(e,t,n){let r=be(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Fn(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=be(t.options.type,t.typeRegistry);if(!o)throw new l(Rt(t.options.type,t.typeRegistry.types,Ot(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return _I(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),HI(e,t,r,n),r}function HI(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let a=wi(t.options.typeOption??[]),i=rr(n,a,t.typeRegistry);if(i.errors.length>0)throw new l(i.errors.join("; "),d.USAGE);e.metadata.type_options=i.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=rr(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function BI(e,t){let n=new Set(t.map(o=>Ti(o))),r=new Set;return e.filter(o=>{if(!n.has(Ti(o)))return!0;let a=sI(o);return r.has(a)?!1:(r.add(a),!0)})}function VI(e,t,n){let r=t.filter(o=>!e.some(a=>ny(a,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function WI(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=BI(r,t.dependencyUpdates.additions);let o=new Set(r.map(a=>Ti(a)));for(let a of t.dependencyUpdates.additions){let i=Ti(a);o.has(i)||(r.push(a),o.add(i))}}t.dependencyRemovals.length>0&&(VI(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(a=>ny(o,a)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function YI(e,t,n){ll(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),ll(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),ll(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function ll(e,t,n,r,o,a){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],a.push(t))}function JI(e,t,n){Vg(e,"files",t.options.file,t.fileUpdates.values,mI,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),XI(e,t,n),Vg(e,"docs",t.options.doc,t.docUpdates.values,pI,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Vg(e,t,n,r,o,a,i,s){if(!(n===void 0&&!i.has(t))){if(a)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(p=>o(p)));for(let p of r){let u=o(p);m.has(u)||(c.push(p),m.add(u))}e.metadata[t]=c}s.push(t)}}function XI(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Wg(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Wg([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Wg(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=uI(r);n.has(o)||(t.push(r),n.add(o))}return t}function QI(e,t,n){let r=t.options.addTags,o=t.options.removeTags,a=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||a){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Pt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=pa(Ln(i,r),o),n.changedFields.push("tags")}dl(wI,t.options,n),eR(e,t,n.changedFields)}function ZI(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let a=ma(Nn(e.metadata.acceptance_criteria),r,o);if(a.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${a.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:a.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=a.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function eR(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=ue(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function tR(e,t,n,r){nR(e,t,n.changedFields),rR(e,t,n.changedFields),dl(vI,t.options,n),Yg(e,t,"sprint",r,n.changedFields),Yg(e,t,"release",r,n.changedFields),oR(e,t,n.changedFields),dl(bI,t.options,n)}function nR(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function rR(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function Yg(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let a=ba(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=a.value,r.push(...a.warnings)}o.push(n)}}function oR(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&dI(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function aR(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=gi(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=yi(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function iR(e,t,n){Jg(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Jg(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,a]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),s=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===o)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${s}`,d.USAGE)}Le(e[o],a)||(e[o]=a,n.push(o))}let r=co(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,a]of Object.entries(r))Le(e[o],a)||(e[o]=a,n.push(o))}function Jg(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function sR(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let a=t[o];return a!==void 0&&(!Array.isArray(a)||!Le(a,n[o]??[]))});if(r!==void 0)throw new l(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,d.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function cR(e,t){sR(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],a=[],i=MI(e,t.options,t.statusRegistry,o),s=e.metadata,c={metadataRecord:s,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};KI(e,t,i,o),zI(e,t,o),WI(e,t,o),YI(e,t,o),JI(e,t,o),QI(e,t,c),ZI(e,t,c),tR(e,t,c,a),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Ur(e.metadata.id,e.metadata.dependencies),te(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),aR(e,t,o),iR(s,t,o);try{lo(s,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new l(u instanceof Error?u.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,p=[...new Set(o)].filter(u=>u==="body"?e.body!==r:!Le(n[u],m[u]));return t.options.acceptanceCriteria!==void 0&&p.includes("acceptance_criteria")&&a.push(`acceptance_criteria_replaced:${Nn(n.acceptance_criteria).length}:${Nn(m.acceptance_criteria).length}`),{changedFields:p,warnings:a}}async function oy(e,t,n,r={}){t=await pl(t);let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=$(a.schema),s=nt(a.schema),c=O(),m=Tt(c),p=x(a,c),u=a.governance.workflow_enforcement??"off",f=u==="off"?[]:Cp(a.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][a.validation.parent_reference],h=Qg(t.unset,s,m),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);ul(t),EI({definitions:SI(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),eI(e,t,g),TI(t,h),CI(t);let w=C(t.author,a.author_default),b=new Date,S=b.toISOString(),T=Ci(t.dep,a.id_prefix,S,w);Ur(e,T.additions);let L=await pn({pmRoot:o,dependencies:T.additions,idPrefix:a.id_prefix,itemFormat:a.item_format,typeToFolder:p.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:a.schema}),P=iI(t.depRemove,a.id_prefix),M=fn("--comment",t.comment,S,w),z=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(R=>({...R,author:w}))}:M,H=fn("--note",t.note,S,w),J=fn("--learning",t.learning,S,w),ee=nl(t.file),Ee=rl(t.test);Ee.values=await zn(Ee.values,w,S);let Qe=ol(t.doc),G=[],pe=await NI({id:e,options:t,unsetTargets:h,pmRoot:o,settings:a,typeRegistry:p,parentReferencePolicy:_}),Ze=await lI(t.blockedBy,g.has("blocked_by"),o,a.id_prefix,a.item_format,p.type_to_folder),Zi=Ze.id,es=[...pe.warnings,...LI(Ze)],tr=oa(t,s,t.runtimeFieldCommands),zt=II(t,tr);if(!Object.values(zt).some(Boolean))return RI({pmRoot:o,id:e,settings:a,typeRegistry:p});G.push(...await $I({options:t,fieldFlags:zt,workflowEnforcement:u,typeWorkflows:f,statusRegistry:i,typeRegistry:p,pmRoot:o,id:e,settings:a}));let Zr=await FI({options:t,fieldFlags:zt,statusRegistry:i,workflowTransitionWarnings:G,global:n,id:e});if(Zr)return Zr;PI(t);let qe=Mt(),St=zt.parent&&!g.has("parent")||T.additions.some(R=>qe.resolve(R.kind)?.hierarchy),eo=await Ja({pmRoot:o,author:w,ttlSeconds:a.locks.ttl_seconds,waitMs:a.locks.wait_ms,required:St});try{let R=await OI({fieldFlags:zt,clearedMetadataKeys:g,pmRoot:o,settings:a,typeToFolder:p.type_to_folder}),Ht,bn,Et=await Zu({pmRoot:o,settings:a,typeToFolder:p.type_to_folder,id:e,op:lR(t,r),author:w,message:t.message,resolveHistoryContext:()=>bn,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(et){Ht=dR({document:et,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),bn=Ht?{recurrence:Ht}:void 0,R=R?.map(to=>to.id===et.metadata.id?structuredClone(et.metadata):to);let ns=cR(et,{options:t,settings:a,typeRegistry:p,statusRegistry:i,runtimeFieldRegistry:s,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:g,dependencyUpdates:T,dependencyRemovals:P,commentUpdates:z,noteUpdates:H,learningUpdates:J,fileUpdates:ee,testUpdates:Ee,docUpdates:Qe,resolvedParentValue:pe.resolvedParentValue,resolvedBlockedByDependencyId:Zi,runtimeFieldUpdates:tr,nowValue:b,nowIso:S,author:w,pmRoot:o});return xI({before:R,document:et,statusRegistry:i}),ns}});await eo();let ts=R?Ga(R,R.map(et=>et.id===Et.item.id?Et.item:et),Et.item.id):[];return{item:Et.item,changed_fields:Et.changedFields,warnings:[...G,...es,...L,...ts,...Et.warnings],...Ht===void 0?{}:{lifecycle_transition:Ht}}}finally{await eo()}}function lR(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function dR(e){if(e.recurrenceReason===void 0)return;let t=te(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!oe(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=te(n,e.statusRegistry)??n,o=e.document.metadata,a=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let s=o[i];return typeof s=="string"?[[i,s]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:a}}async function it(e,t,n){return oy(e,t,n)}async function ay(e,t,n,r){let o=await oy(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90a2e91a-50cf-5ad9-87ef-fa95cabf125d")}catch{}})();async function fl(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.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 a=E(process.cwd(),r.path),i=$((await A(a)).schema),s=i.open_status,c=Ei(i),m=n.status??s,p=te(m,i)??m;if(p!==s&&p!==c)throw new l(`Reopen target status must be ${s} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([s,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${s}`,suggested_retry_args:["item","reopen",e,o,"--status",s]}});let u=await ay(e,{status:p,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:u.item,changed_fields:u.changed_fields,warnings:u.warnings,recurrence:u.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56177893-3ccb-5b3f-aa82-9365c26c5d34")}catch{}})();async function iy(e,t,n){return[...await Promise.resolve().then(()=>Au(tt(e,t),t)).catch(()=>[])].reverse().find(r=>r.patch.some(o=>o.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ce03100c-3a4f-5ce4-a216-a3fabcfc655e")}catch{}})();var sy="no_available_next_item";function cy(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function Gr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=$(a.schema),s=C(r.author,a.author_default),c=Pn(s),m=null,p=!1,u=[],f=await ce({pmRoot:o,settings:a,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let h=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||h;if(m=h.trim().length>0?h:null,kp(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&y!==c){if(r.ifAvailable===!0)return p=!0,u.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let b=await iy(o,_.metadata.id,h);throw new l(`Item ${_.metadata.id} is already ${b}. Use --force to take over, or --if-available to skip without failing.`,d.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${m}->${s}`)}let g={assignee:s,claim_principal:c},w=["assignee","claim_principal"].filter(b=>_.metadata[b]!==g[b]);return Object.assign(_.metadata,g),{changedFields:w,warnings:u}}});return p||await gc({pmRoot:o,settings:a,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:p&&m!==null?m:s,previous_assignee:m,forced:t,...p?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function ly(e,t,n={},r={}){let o=mR(n.maxAttempts),a=await A(E(process.cwd(),t.path)),i={...n,author:C(n.author,a.author_default)},s=await Ir({...r,callerAuthor:i.author,limit:String(o)},t),c=[s.recommended,...s.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return pR(c.slice(0,o),e,t,i)}function mR(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function pR(e,t,n,r={},o=Gr){let a=0;for(let s of e){a+=1;try{let c=await o(s.id,t,n,r),m={...c,recommendation:s,attempts:a,available:!0};if(!c.skipped)return m}catch(c){if(!cy(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:a,warnings:[sy]};let i=a===0;throw new l(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?d.NOT_FOUND:d.CONFLICT,{code:sy,why:i?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[i?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function jr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let a=await A(o),i=C(r.author,a.author_default),s=Pn(i),c=r.ownershipReleaseBypass===!0,m=null,p;try{p=await ce({pmRoot:o,settings:a,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){Nr(_,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await yc({pmRoot:o,principal:s,itemId:p.item.id});let u=$(a.schema),f=js(p.item.status,u)===js(u.in_progress_status,u);return{item:p.item,released_by:i,changed_fields:p.changedFields,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${p.item.id} remains ${p.item.status} and unclaimed. If work is paused, run pm release ${p.item.id} --pause to move it to ${u.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfa2b84f-fb12-53ec-b205-ad69e694bf12")}catch{}})();async function _l(e,t,n){try{return await n()}catch(r){let o=r instanceof l?r.context:{},a=new l(r instanceof Error?r.message:String(r),r instanceof l?r.exitCode:d.GENERIC_FAILURE,{...o,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${o.why?` ${o.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...o.nextSteps??[]]});throw a.cause=r,a}}async function hl(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start requires an explicit item id and cannot be combined with --next or --if-available",d.USAGE);let r=await A(E(process.cwd(),n.path)),o=Ei($(r.schema)),a=await Gr(e,t.force===!0,n,t),i=a.item.id,s=await _l(i,"claim",()=>it(i,Dt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:i,action:"start_task",claim:a,update:s}}async function gl(e,t,n){let r=await A(E(process.cwd(),n.path)),o=$(r.schema).open_status,a=await it(e,Dt(t,{status:o},["assignee","pause"]),n),i=a.item.id,s=await _l(i,"update",()=>jr(i,t.force===!0,n,t));return{id:i,action:"pause_task",update:a,release:s}}async function yl(e,t,n,r){let o=await wt(e,t,n,r),a=o.item.id,i=await _l(a,"close",()=>jr(a,n.force===!0,r,n));return{id:a,action:"close_task",close:o,release:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="140b50c9-b0b3-5446-8ef9-5993bf4d830c")}catch{}})();async function dy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=e.force===!0||r.force===!0,a={...e.args,...r};if(a.start===!0)return _n(e,"start_task");let i=e.args.next===!0||r.next===!0?await ly(o,e.global,a,a):await Gr(qr(e,r),o,e.global,a);return Se(i,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function qr(e,t){let n=e.id??v(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function wl(e,t){return v(e.args,"reason")??v(e.args,"text")??v(t,"reason")??v(t,"text")}async function my(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return r.releaseAssignment===!0?_n(e,"close_task"):Se(await wt(qr(e,r),wl(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function _n(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=_e(e.args,e.options),a=qr(e,o),i=Dt(o,{force:e.force===!0||o.force===!0}),s=t==="start_task"?await hl(a,i,e.global):t==="pause_task"?await gl(a,i,e.global):await yl(a,wl(e,o),i,e.global);return Se(s,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function py(e){if(e.options.pause===!0)return _n(e,"pause_task");let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=await jr(qr(e,r),e.force===!0,e.global,r);return Se(o,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function uy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await fl(qr(e,r),wl(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a610a47-2af8-51b7-a8ab-2557eaf611e2")}catch{}})();function Ii(e,t){let n=Zt(["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(r=>r.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(r=>r.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${qp(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1e5721e-92fd-5c2e-989f-d63892ed9d90")}catch{}})();var uR=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],fy=["brief","standard","deep"],gy="plan-step-",Al="draft",El=["bug-investigation","feature-implementation","refactoring-sprint"],_y={"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 fR(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(_y,t)?_y[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${El.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${El[0]}`]});return n.map(r=>({...r}))}function _R(e,t){return t>0?Math.round(e/t*100):0}function yy(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(t=>t!=null).map(t=>(typeof t=="string"?t:String(t)).trim()).filter(t=>t.length>0)}function ze(e){return Array.isArray(e)?e.flatMap(t=>Un(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Un(e,{unique:!1}):[]}function Pe(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function wy(e,t=Al){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ms.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${ms.join(", ")}`,d.USAGE);return r}function Tl(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ps.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${ps.join(", ")}`,d.USAGE);return r}function vy(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=fs.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${fs.join(", ")}`,d.USAGE);return r}function hR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=us.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${us.join(", ")}`,d.USAGE);return n}function gR(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=fy.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${fy.join(", ")}`,d.USAGE);return n}function yR(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 l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var vl=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function wR(e,t){let n=e,r={},o=[];for(let a of t){let i=a.startsWith("plan.")?a.slice(5):a;if(i.length!==0){if(!vl.has(i)){o.push(a);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...vl].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...vl].join(",")}`}});return r}function Cl(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let a=o.indexOf("=");if(a<=0)throw new l(`Invalid ${t} entry "${o}"; expected key=value`,d.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[o.slice(0,a).trim().toLowerCase()]=o.slice(a+1).trim()}return n}function Il(e){let t=Cl(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.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 Rl(e){let t=Cl(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.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 Ol(e){let t=Cl(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.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 vR(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=_R(t.completed,t.total),t}function bR(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${gy}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Yn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),a=e.find(i=>i.order===o);if(a)return a}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function hy(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 kR(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((s,c)=>s.order-c.order)){let s=hy(i);if(s){o.push({from_step:i.id,...s});continue}r.push(i)}return{targets:r,skipped:o}}let a=new Set;for(let i of t){let s=Yn(e,i);if(a.has(s.id))continue;a.add(s.id);let c=hy(s);if(c){o.push({from_step:s.id,...c});continue}r.push(s)}return{targets:r,skipped:o}}function SR(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function ER(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function AR(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 Ue(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,s)=>i.order-s.order),r=vR(n),o=ER(n),a={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Al,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:AR(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(a.steps=n),t==="deep"&&(a.decisions=e.plan_decisions??[],a.discoveries=e.plan_discoveries??[],a.validation=e.plan_validation??[]),a}function Ge(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&&!ec(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function by(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.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 TR(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function ky(e,t){let n=x(e.settings,O()),r=await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let o=await se(r,{schema:e.settings.schema});return by(o.document.metadata),{document:o.document,itemId:r.id}}function CR(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of ze(e.related))t.push(`id=${n},kind=related`);for(let n of ze(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of ze(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function IR(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function RR(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||ze(e.dependsOn).length>0||ze(e.link).length>0}function OR(e){let t=e.stepTitle?.trim()||void 0,n=yy(e.step),r=e.template?.trim()?fR(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function xR(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${El[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.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 PR(e,t){let n=Tl(e.stepStatus,"pending"),r=xl(e,"depends_on"),o=Pe(e.file).map(Il),a=Pe(e.test).map(Rl),i=Pe(e.doc).map(Ol),s=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:a.length>0?a:void 0,docs:i.length>0?i:void 0,created_at:s,updated_at:s,completed_at:n==="completed"?s:void 0}}function NR(e){let t=OR(e),n=RR(e);if(xR(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[PR(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,a)=>({id:`${gy}${String(a+1).padStart(3,"0")}`,order:a+1,title:o,body:t.templateSteps[a]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Sy(e,t,n=[]){Ie(e,t),n.length>0&&ju(t,n)}async function LR(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=wy(e.mode,Al),a=hR(e.harness),i=e.fromSearch?.trim(),s=IR(e),{steps:c,hasPerStepDetailOptions:m}=NR(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let p=e.description?.trim()??e.scope?.trim()??r,u=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:p,type:"Plan",template:void 0,file:Pe(e.file),test:Pe(e.test),doc:Pe(e.doc),field:Pe(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:CR(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")};Sy(e,f);let _=await Gt(f,t),h=await ce({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let w=["plan_mode"];g.metadata.plan_mode=o,a&&(g.metadata.plan_harness=a,w.push("plan_harness"));let b=e.scope?.trim();b&&(g.metadata.plan_scope=b,w.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(g.metadata.plan_resume_context=S,w.push("plan_resume_context")),g.metadata.plan_steps=c,w.push("plan_steps"),s&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],s],w.push("plan_validation")),u&&(g.metadata.assignee=u,w.push("assignee")),{changedFields:w}}}),y=Ue(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ge(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function $R(e,t,n){let r=gR(t.depth),o=yR(t.fields),{document:a,itemId:i}=await ky(n,e),s=Ue(a.metadata,o===null?r:"deep");return{action:"show",plan:o===null?s:wR(s,o),next_actions:Ge(i,s),warnings:[],generated_at:k()}}function FR(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function st(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await ce({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(o){by(o.metadata);let a=$(e.ctx.settings.schema);if(oe(o.metadata.status,a)||ec(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.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 i=(o.metadata.plan_steps??[]).slice(),s=new Map(Object.entries(o.metadata).filter(([u])=>u.startsWith("plan_")).map(([u,f])=>[u,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let m=i.slice().sort((u,f)=>u.order-f.order).map((u,f)=>({...u,order:f+1}));o.metadata.plan_steps=m;let p=FR(s,o.metadata);return p.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:p.length>0?p:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function MR(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Tl(t.stepStatus,"pending"),a=t.allowMultipleActive===!0,{document:i,resultStep:s,itemId:c}=await st({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(p){let u=p.length+1;Ey(p,void 0,o,a);let f=DR(p,t,{order:u,title:r,status:o});return p.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Ue(i.metadata,"standard");return{action:"add-step",plan:m,step:s,next_actions:Ge(c,m),warnings:[],generated_at:k()}}function Ey(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(a=>a.id!==t&&a.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function DR(e,t,n){let r=xl(t,"depends_on"),o=Pe(t.file).map(Il),a=Pe(t.test).map(Rl),i=Pe(t.doc).map(Ol),s=k();return{id:bR(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:a.length>0?a:void 0,docs:i.length>0?i:void 0,created_at:s,updated_at:s,completed_at:n.status==="completed"?s:void 0}}function xl(e,t){let n=ze(e.dependsOn).map(p=>({id:p,kind:t})),r=ze(e.related).map(p=>({id:p,kind:"related"})),o=ze(e.blocks).map(p=>({id:p,kind:"blocks"})),a=ze(e.blockedBy).map(p=>({id:p,kind:"blocked_by"})),i=ze(e.link),s=vy(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(p=>{let u={id:p,kind:s};return c&&(u.note=c),u});return[...n,...r,...o,...a,...m]}async function bl(e,t,n,r){let{document:o,resultStep:a,itemId:i}=await st({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let p=Yn(c,r.stepRef),u=k(),f=r.finalStatus??Tl(t.stepStatus,p.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return Ey(c,p.status==="in_progress"?p.id:void 0,f,_),UR(p,t,f,u),m.metadata.updated_at=u,{changedSteps:[p.id],resultStep:p}}}),s=Ue(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:s,step:a,next_actions:Ge(i,s),warnings:[],generated_at:k()}}function UR(e,t,n,r){GR(e,t,n),jR(e,t),e.status=n,e.updated_at=r,qR(e,n,r)}function GR(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function jR(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=t.stepOwner.trim()||void 0),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 r=Pe(t.file).map(Il),o=Pe(t.test).map(Rl),a=Pe(t.doc).map(Ol);r.length>0&&(e.files=kl(e.files,r)),o.length>0&&(e.tests=kl(e.tests,o)),a.length>0&&(e.docs=kl(e.docs,a))}function kl(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let a=JSON.stringify(o);r.has(a)||(r.add(a),n.push(o))}return n}function qR(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function KR(e,t,n,r,o){let{document:a,itemId:i,resultStep:s}=await st({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(m){let p=Yn(m,r),u=m.filter(_=>_.id!==p.id),f=Math.max(1,Math.min(o,u.length+1));return u.splice(f-1,0,p),u.forEach((_,h)=>{_.order=h+1,_.updated_at=k()}),m.length=0,m.push(...u),{changedSteps:[p.id],resultStep:p}}}),c=Ue(a.metadata,"standard");return{action:"reorder-step",plan:c,step:s,next_actions:Ge(i,c),warnings:[],generated_at:k()}}async function zR(e,t,n,r){let{document:o,itemId:a,resultStep:i}=await st({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let m=Yn(c,r),p=c.filter(u=>u.id!==m.id);return p.forEach((u,f)=>{u.order=f+1}),c.length=0,c.push(...p),{changedSteps:[m.id],resultStep:m}}}),s=Ue(o.metadata,"standard");return{action:"remove-step",plan:s,step:i,next_actions:Ge(a,s),warnings:[],generated_at:k()}}async function HR(e,t,n,r){let o=xl(t,vy(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let a=t.promoteToItemDep===!0,{document:i,itemId:s,resultStep:c}=await st({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(p,u){let f=Yn(p,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of o){let w=h(g);y.has(w)||(_.push(g),y.add(w))}if(f.linked_items=_,f.updated_at=k(),a){let g=u.metadata.dependencies??[],w=S=>`${S.kind}:${S.id}`,b=new Set(g.map(w));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,L={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};b.has(w(L))||(g.push(L),b.add(w(L)))}u.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=Ue(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ge(s,m),warnings:[],generated_at:k()}}async function BR(e,t,n,r){let o=ze(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:a,itemId:i,resultStep:s}=await st({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let p=Yn(m,r),u=(p.linked_items??[]).filter(f=>!o.includes(f.id));return p.linked_items=u.length>0?u:void 0,p.updated_at=k(),{changedSteps:[p.id],resultStep:p}}}),c=Ue(a.metadata,"standard");return{action:"unlink",plan:c,step:s,next_actions:Ge(i,c),warnings:[],generated_at:k()}}async function Sl(e,t,n,r){let o=SR(r,t);if(!o){let m=`--${r}-text`,p=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${p} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let a=C(t.author,n.settings.author_default),{document:i,itemId:s}=await st({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,p){let u=k();if(r==="decision"){let _=p.metadata.plan_decisions??[];return _.push({ts:u,author:a,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),p.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=p.metadata.plan_discoveries??[];return _.push({ts:u,author:a,text:o}),p.metadata.plan_discoveries=_,{changedSteps:[]}}let f=p.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),p.metadata.plan_validation=f,{changedSteps:[]}}}),c=Ue(i.metadata,"deep");return{action:r,plan:c,next_actions:Ge(s,c),warnings:[],generated_at:k()}}async function VR(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:a}=await st({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(s,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Ue(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Ge(a,i),warnings:[],generated_at:k()}}async function WR(e,t,n){let r=wy(t.mode??"approved","approved"),{document:o,itemId:a}=await st({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(s,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Ue(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Ge(a,i),warnings:[],generated_at:k()}}function Ay(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function YR(e,t){let n=Ue(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ge(e.itemId,n),warnings:Ay(t),generated_at:k()}}function JR(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let a=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${a}`)}return r}async function XR(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Pe(e.options.field)){let a=o.indexOf("=");if(a<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let i=o.slice(0,a).trim(),s=o.slice(a+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let c=i.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 l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let[m,...p]=c,u=`${m}${p.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(u))throw new l(`Invalid --field entry "${o}"; "${u}" is reserved by materialize and cannot be overridden`,d.USAGE);n[u]=s}for(let o of e.targets){let a={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:JR(e.parent,e.planItemId,o)};Sy(e.options,a,["description",...Object.keys(n)]);let i=await Gt(a,{path:e.pmRoot});t.push({id:i.item.id,title:i.item.title,type:e.resolvedTypeName,parent:i.item.parent,tags:i.item.tags??[],from_step:o.id})}return t}function QR(e,t,n){for(let r of t){let o=n.find(s=>s.from_step===r.id);if(!o)continue;let a=e.find(s=>s.id===r.id);if(!a)continue;let i=a.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),a.linked_items=i,a.updated_at=k()}}async function ZR(e,t,n){let r=ze(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",a=x(n.settings,O()),i=be(o,a);if(!i)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let s=t.materializeParent?.trim()||e,c=t.materializeTags,m=await ky(n,e),p=(m.document.metadata.plan_steps??[]).slice(),{targets:u,skipped:f}=kR(p,r);if(u.length===0){if(f.length>0)return YR(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await XR({targets:u,parent:s,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await st({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return QR(w,u,_),{changedSteps:u.map(b=>b.id)}}}),g=Ue(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ge(y,g),warnings:Ay(f),generated_at:k()}}function eO(e){if(e.subcommand==="create")return e;let t=yy(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:Ie(e.options,{...e.options,stepTitle:t[0]})}:e}function bt(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function hn(e,t){let n=bt(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function tO(e){let t=hn(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var nO={create:(e,t)=>LR(e.options,e.global,t),show:(e,t)=>$R(bt(e,"show"),e.options,t),"add-step":(e,t)=>MR(bt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=hn(e,"update-step");return bl(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=hn(e,"complete-step");return bl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=hn(e,"block-step");return bl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=tO(e);return KR(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=hn(e,"remove-step");return zR(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=hn(e,"link");return HR(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=hn(e,"unlink");return BR(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Sl(bt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Sl(bt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Sl(bt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>VR(bt(e,"resume"),e.options,t),approve:(e,t)=>WR(bt(e,"approve"),e.options,t),materialize:(e,t)=>ZR(bt(e,"materialize"),e.options,t)};function rO(e){let t=nO[e];if(!t)throw Ce({command_path:"plan",token:e,allowed:uR});return t}async function Ty(e){let t=await TR(e.global),n=eO(e),r=await rO(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Ii(r,t.pmRoot)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a59a772-3e2a-5ae2-88c1-a96bc36f9f85")}catch{}})();var Iy=1,Nl="update-many",oO=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),aO=["--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(", "),iO={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"},sO=[{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"}],cO={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},Ry=e=>{let t={};for(let[n,r]of Object.entries(e))oO.has(n)||r!==void 0&&(t[n]=r);return t},lO=e=>Object.keys(Ry(e)).length>0,Oy=e=>typeof e=="string"?e.trim():e,dO=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Pl=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},mO=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Oy(e)},pO={priority:dO,estimatedMinutes:Pl,order:Pl,rank:Pl,regression:mO},uO=(e,t)=>{if(t!==void 0)return(pO[e]??Oy)(t)},fO=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return cO[t]??t},Ri=(e,t)=>Le(e,t),_O=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],hO=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,gO=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Cy=(e,t)=>t===void 0?void 0:e[t],Jn=e=>Array.isArray(e)?e.length:0,yO=(e,t,n)=>{let r=n[e.addKey],o=Cy(n,e.removeKey),a=Jn(r),i=Jn(o),s=n[e.clearKey]===!0,c=Cy(n,e.replaceKey)===!0;if(![s,c,a>0,i>0].includes(!0))return;let m=_O(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:gO({replace:c,clear:s,removeCount:i}),clear:s,replace:c,add_count:a,remove_count:i,before_count:hO(e.field,m)}}},wO=(e,t)=>{let n=[];for(let r of sO){let o=yO(r,e,t);o!==void 0&&n.push(o)}return n},vO=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],bO=(e,t)=>{if(![t.tags!==void 0,Jn(t.addTags)>0,Jn(t.removeTags)>0].includes(!0))return;let n=vO(e.tags),r=t.tags===void 0?n:Pt(t.tags),o=Ln(r,t.addTags),a=pa(o,t.removeTags).slice().sort((s,c)=>s.localeCompare(c)),i=n.slice().sort((s,c)=>s.localeCompare(c));if(!Ri(i,a))return{field:"tags",before:n,after:a}},kO=(e,t)=>{let n=e.acceptance_criteria,r=ma(Nn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!Ri(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},SO=(e,t,n)=>{for(let[r,o]of Object.entries(iO)){let a=n[r];if(a===void 0)continue;let i=t[o],s=uO(r,a);Ri(i,s)||e.push({field:o,before:i,after:s})}},EO=(e,t,n,r)=>{let o=oa(n,r,["update_many"]);for(let[a,i]of Object.entries(o)){let s=t[a];Ri(s,i)||e.push({field:a,before:s,after:i})}},AO=(e,t,n)=>{for(let r of n??[]){let o=fO(r),a=t[o];a!==void 0&&e.push({field:o,before:a,after:null})}},TO=(e,t,n={})=>{let r=e,o=[],a=bO(r,n);if(a&&o.push(a),SO(o,r,n),Jn(n.addAc)>0||Jn(n.removeAc)>0){let i=kO(r,n);i!==void 0&&o.push(i)}return o.push(...wO(r,n)),EO(o,r,n,t),AO(o,r,n.unset),{id:e.id,changes:o}},CO=(e,t)=>Bu(e,t,{strict:!0,flagLabel:"--filter-status"}),IO=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},RO=[({update:e})=>{e.priority!==void 0&&Fn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,O());if(!be(e.type,r))throw new l(Rt(e.type,r.types,Ot(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!te(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&ie(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&$n(e.estimatedMinutes,"estimated-minutes")}],OO=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let a of RO)a(o)},xO=async e=>{let t=await ca(e.pmRoot,Nl,e.rollbackId,Iy),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await la(t.items,(o,a)=>an(o,a,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...en({applied:r.restored_ids.length,skipped:0,failed:r.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:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},PO=async e=>{let t={schema_version:Iy,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 sa(e.pmRoot,Nl,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},NO=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Ll=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},LO=async e=>{let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:$(n.schema),runtimeFieldRegistry:nt(n.schema)}},$O=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Cr(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return xO({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},FO=async e=>{CO(e.options.status,e.runtime.statusRegistry);let t=await ht(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(o=>{let a=TO(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?a:{...a,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await ht(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:NO(e.options.list?.ids,r)}},MO=e=>({outcome:"effect",exit_code:d.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:[],...Ll(e)}),DO=e=>({...en({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:[],...Ll(e)}),UO=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(a=>a.changes.length>0).map(a=>a.id));for(let a of e.items){if(!o.has(a.id)){t.push({id:a.id,status:"skipped"});continue}try{let i=Xs({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),s=await it(a.id,i,e.global);t.push({id:a.id,status:"updated",changed_fields:s.changed_fields,warnings:s.warnings}),n.push(a.id)}catch(i){t.push({id:a.id,status:"failed",error:An(i)})}}return{rows:t,updatedIds:n}},GO=async e=>{if(e.plan.actionable.length===0)return DO(e.plan);let t=k(),n=ia(Nl,t),r=new Set(e.plan.actionable.map(u=>u.id)),o=e.plan.listed.items.filter(u=>r.has(u.id)).map(u=>({id:u.id,target_updated_at:u.updated_at})),a=e.options.checkpoint===!1?void 0:await PO({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:o}),i=await UO({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),s=u=>i.rows.filter(f=>f.status===u).length,c=s("updated"),m=s("skipped"),p=s("failed");return{...en({applied:c,skipped:m,failed:p,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,...a?{checkpoint:a}:{},updated_count:c,skipped_count:m,failed_count:p,rows:i.rows,ids:i.updatedIds,...Ll(e.plan)}},xy=async(e,t)=>{let n=await LO(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Xs(await pl(e.update))});let o=Ry(e.update);if(IO(e.list),r!==void 0)return $O({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!lO(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${aO}), or pass --dry-run for a filter-only preview.`,d.USAGE);OO(e.update,n.settings,n.statusRegistry,n.pmRoot),ul(e.update);let a=await pn({pmRoot:n.pmRoot,dependencies:Ci(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await FO({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:a});return await pn({pmRoot:n.pmRoot,dependencies:Ci(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(s=>({id:s.id,createdAt:s.created_at})),schema:n.settings.schema}),e.dryRun===!0?MO(i):GO({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6263346a-08ee-5eb9-81b9-47e933793c07")}catch{}})();function jO(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function qO(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 KO(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function Py(e,t,n){let r=jO(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let a=r===void 0?void 0:Yt(r),i=[t.since,t.eventType].some(h=>h!==void 0),s=KO(t.since),c=gr(t.limit),m=await Bn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await Wa(a===void 0?t:{add:a},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Hn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:qO(r)},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."]}}),p=t.eventType?.trim(),u=m.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[s===void 0,Date.parse(h.created_at)>=(s??Number.POSITIVE_INFINITY)].includes(!0),w=[!p,h.event_type===p].includes(!0);return[!i,[y,g,w].every(Boolean)].includes(!0)}),f=i?Pc(u,c):u,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:u.length,returned_count:f.length,has_more:f.length<u.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}import nx from"node:path";import zO from"node:fs/promises";import Ny from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ac2020a4-78bf-5aa3-a5c4-88d3196dfb1f")}catch{}})();var HO="templates",BO=".json",VO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,WO=Zo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),YO=new Set(WO);function JO(e){let t=e.trim();if(!VO.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function Ly(e){return Ny.join(e,HO)}function $y(e,t){return Ny.join(Ly(e),`${t}${BO}`)}async function XO(e){await I(e)}function Fy(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function QO(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(YO.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(a=>typeof a=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return Fy(t)}function ZO(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[o,a]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof a=="string"){r[i]=a;continue}if(Array.isArray(a)&&a.every(s=>typeof s=="string")){r[i]=[...a];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return Fy(r)}function ex(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,o=ZO(r.options,t),a=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:a,updated_at:typeof r.updated_at=="string"?r.updated_at:a,options:o}}async function tx(e,t){let n=await X($y(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return ex(n,t)}async function $l(e,t,n){let r=E(process.cwd(),n.path);await XO(r);let o=JO(e),a=QO(t);if(Object.keys(a).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=k(),s=$y(r,o),c=i;await j(s)&&(c=(await tx(r,o)).created_at);let m={name:o,created_at:c,updated_at:i,options:a},p=await A(r);return await zO.mkdir(Ly(r),{recursive:!0}),await Ve({pmRoot:r,filePath:s,raw:`${JSON.stringify(m,null,2)}
23
+ `,op:"templates:save",author:C(void 0,p.author_default),lockTtlSeconds:p.locks.ttl_seconds,lockWaitMs:p.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:s,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa4e2ff3-dc3b-5688-bf40-bdd71c65320b")}catch{}})();var Gy=["list","show","apply","lint"],rx="schema-types",ox="schema-statuses",ax="schema-fields";function Oi(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function jy(){let{profiles:e,warnings:t}=wp(Oi());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:Ep(n.definition)})),warnings:t,generated_at:k()}}function qy(e){let t;try{t=Ko(e,Oi())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...Ap(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function Ky(e){let t;try{t=Ko(e,Oi())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=eu(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function ix(e,t){return nx.join(e,"templates",`${t}.json`)}async function sx(e,t){let n=await X(ix(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function My(e,t,n,r){let o=new Map;for(let a of r.templates){let i=await sx(e,a.name);i!==void 0&&o.set(a.name,i)}return{typesRaw:await X(pt(e,t.files.types,mt.types)),statusesRaw:await X(pt(e,t.files.statuses,mt.statuses)),fieldsRaw:await X(pt(e,t.files.fields,mt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Xn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Dy(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Xn(t.types.changes),statuses:Xn(t.statuses.changes),fields:Xn(t.fields.changes),workflows:Xn(t.workflows.changes.map(a=>({key:a.type,status:a.status}))),config:Xn(t.config.changes),templates:Xn(t.templates.changes.map(a=>({key:a.name,status:a.status}))),packages:t.packages,warnings:[...new Set(o)].sort((a,i)=>a.localeCompare(i)),generated_at:k()}}async function cx(e){await I(e)}function lx(e){try{let t=Ko(e,Oi());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function zy(e,t,n){let r=E(process.cwd(),n.path);await cx(r);let o=lx(e),a=o.profile,i=o.warnings,s=t.dryRun===!0,c=await A(r),m=zo(c.schema);if(s){let w=await My(r,m,c,a),b=Uy(a,w);return Dy(a,b,!1,!0,[...i])}let p=C(t.author,c.author_default),u=Du(c),f=!!t.force,_=[...i],h=[],y=async w=>{h.push(await Te(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(rx),await y(ox),await y(ax);let w=await My(r,m,c,a);if(g=Uy(a,w),g.types.changed){let b=pt(r,m.files.types,mt.types);await Ve({pmRoot:r,filePath:b,raw:qo(g.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(a.types.map(L=>up(L).name)),T=g.types.file.definitions.filter(L=>S.has(L.name));await Tf(r,T,_,"profile:apply-type-folder"),_.push(...await Y({path:b,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let b=pt(r,m.files.statuses,mt.statuses);await Ve({pmRoot:r,filePath:b,raw:Sp(g.statuses.file),op:"profile:apply-statuses",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let b=pt(r,m.files.fields,mt.fields);await Ve({pmRoot:r,filePath:b,raw:vp(g.fields.file),op:"profile:apply-fields",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let b of g.config.changes){if(b.status==="unchanged")continue;let S=Bo(b.key);S!==void 0&&Vo(c,S,b.value)}c.schema.type_workflows=g.workflows.result,await Fe(r,c,"profile:apply-config")}for(let b of g.templates.changes)b.status!=="unchanged"&&await $l(b.name,{...b.options},n)}finally{for(let w of h.reverse())try{await w()}catch{}}return Dy(a,g,g.changed,!1,_)}function Uy(e,t){try{return tu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import hx from"node:fs/promises";import Dl from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c34cc860-67c7-548b-99ff-f4155ef44bb0")}catch{}})();var By=10,gn="https://schema.unbrained.dev/pm/eval-query-set/v1";var xi={schema:gn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Je=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},dx=new Set(["keyword","semantic","hybrid"]);function Hy(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function mx(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=Hy(r,n),a=Array.from({length:t.size},()=>1),i=Hy(a,n);return i===0?0:o/i}function px(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function Fl(e,t,n){let r=Math.min(n,e.length),o=0;for(let a=0;a<r;a+=1)t.has(e[a])&&(o+=1);return o}function ux(e,t,n){return n<=0?0:Fl(e,t,n)/n}function fx(e,t,n){return t.size===0?0:Fl(e,t,n)/t.size}function Vy(e,t,n){return{ndcg:mx(e,t,n),mrr:px(e,t,n),precision:ux(e,t,n),recall:fx(e,t,n),relevant_total:t.size,retrieved_relevant:Fl(e,t,n)}}function Wy(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function _x(e,t){if(typeof e!="object"||e===null)throw new Je(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Je(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Je(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(a=>typeof a!="string"))throw new Je(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(a=>a.trim()).filter(a=>a.length>0))];if(o.length===0)throw new Je(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!dx.has(n.mode)))throw new Je(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:U_(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Ml(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==gn)throw new Je(`Unsupported eval query set schema; expected "${gn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Je('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Je("Eval query set must contain at least one query");return{schema:gn,queries:n.map((r,o)=>_x(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();var gx=Dl.join("search","eval-queries.json"),Ul={schema:gn,examples:[JSON.stringify(xi)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},yx=new Set(["keyword","semantic","hybrid"]),wx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!yx.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},vx=e=>{if(e===void 0||e==="")return By;let t=Xd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},bx=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},jt=e=>Math.round(e*1e4)/1e4,kx=async e=>{try{return await hx.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ul,examples:[`echo '${JSON.stringify(xi)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},Sx=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Ul)}},Ex=e=>{try{return Ml(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ul)}},Ax=async e=>Ex(Sx(await kx(e),e)),Tx=async(e,t,n,r)=>{let o=e.mode??t,a=(await Rr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),i=Vy(a,new Set(e.relevant_ids),n);return{metrics:i,report:{query:e.query,...e.minimum===void 0?{}:{violations:G_(i,e.minimum)},mode:o,relevant_total:i.relevant_total,retrieved_relevant:i.retrieved_relevant,ndcg:jt(i.ndcg),mrr:jt(i.mrr),precision:jt(i.precision),recall:jt(i.recall)}}},Cx=(e,t,n,r)=>{let o=Wy(n);return{k:e,query_count:t.length,aggregate:{ndcg:jt(o.ndcg),mrr:jt(o.mrr),precision:jt(o.precision),recall:jt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:(r===void 0||o.ndcg>=r)&&t.every(a=>(a.violations?.length??0)===0)}},Yy=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=vx(e.k),o=wx(e.mode),a=bx(e.failUnder),i=e.queries?Dl.resolve(process.cwd(),e.queries):Dl.join(n,gx),s=await Ax(i),c=[],m=[];for(let p of s.queries){let{report:u,metrics:f}=await Tx(p,o,r,t);m.push(f),c.push(u)}return Cx(r,c,m,a)};import{readFile as Ix,writeFile as Rx}from"node:fs/promises";import Ox from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abbd522e-582e-584b-bf25-e065173918f4")}catch{}})();var Jy=["item","history","relationship","json"];function xx(e){let t=e.trim().toLowerCase();if(Jy.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${Jy.join(", ")}.`,d.USAGE)}function Px(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function Gl(e,t){try{return await Ix(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function Nx(e){let t=E(process.cwd(),e.path);return await j(re(t))?A(t):null}function Lx(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Xy(e,t){let n=xx(e.artifact),r=Px(e.prefer),o=Ox.resolve(e.outputPath??e.oursPath),[a,i,s]=await Promise.all([Gl(e.basePath,"base"),Gl(e.oursPath,"ours"),Gl(e.theirsPath,"theirs")]),c,m,p=[],u={};if(n==="history"){let _=r_(a,i,s);c=_.merged,u.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=o_(a,i,s);c=_.merged,u.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await Nx(t),h=Lx(e.itemPath??o,_),y=Tt(O()),g=a_(a,i,s,{format:h,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=g.merged,p.push(...g.conflict_fields),u.item={fields_from_theirs:g.fields_from_theirs,union_fields:g.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let w=Su(c,{format:h,schema:_?.schema,extensionFieldNames:y}),b=w.metadata,S=[...new Set([...g.fields_from_theirs,...g.union_fields,...g.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:g.fields_from_theirs,unionFields:g.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,n_(T==="body"?w.body:b[T])])),decisions:g.conflict_decisions,operation:await s_(process.cwd(),e.itemPath)}}}else{let _=i_(a,i,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await Rx(o,c,"utf8"),m!==void 0){let _=await l_(m);_!==null&&(u.receipt=nn(_))}let f=[];if(p.length>0){let _=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${p.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. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.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:p.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:p,...u,guidance:f,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="450eabe6-334a-587c-b838-5ca42519296f")}catch{}})();async function Qy(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await c_(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Ut(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Ut(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??"Settle rebase receipt after exact original Git state restoration",auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...nn(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await La(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as $x}from"node:fs/promises";import Fx from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b07f6f1-2c84-583c-afb2-80f219d19863")}catch{}})();var Mx=4;function Zy(e){let t=e.checks.find(s=>s.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,a=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,i=Array.isArray(o)?o.flatMap(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return[];let c=s;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:r,truncated:a,coordinates:i}}async function Dx(e,t){let n=[];for(let r of t){let o;try{o=await $x(Fx.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let a=o.split(/\r?\n/)[r.history_line-1];if(a===void 0||a.trim().length===0)continue;let i;try{i=JSON.parse(a)}catch{continue}let s=f_(i,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!u_(s)||s.eventTimestamp===void 0||Xo(s.eventTimestamp,p_)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function Ux(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 r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Ut(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:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function Gx(e){try{return{status:"fulfilled",value:await Ut(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 jx(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,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[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function qx(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>La(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}async function ew(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await Ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),a=Zy(o),i=await Dx(r,a.coordinates),s=await Ca(r),c=s??r,m=await d_(c,{includeLossless:!0,pmRoot:r});if(m.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${m.invalid_evidence_count} invalid receipt evidence file(s).`,d.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"}});let p=await Ux({candidates:i,options:e,global:t}),u=m.receipts,f=await Qy({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),_=new Set(f),h=new Map;for(let G of u.filter(pe=>!_.has(pe.id))){let pe=h.get(G.item_id)??[];pe.push(G),h.set(G.item_id,pe)}let y=Object.fromEntries([...h].map(([G,pe])=>[G,{merge:{receipts:pe.map(nn)}}])),g=Object.fromEntries([...h].map(([G,pe])=>[G,{gitWorkspaceRoot:s,receipts:pe}])),w=await Fa({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:y,...u.length>0?{mergeReceiptProofById:g}:{}},t),b=new Set(w.streams.map(G=>G.id)),S=[...h.keys()].filter(G=>!b.has(G)),T=await Df(S,Mx,G=>Gx({id:G,dryRun:n,options:e,global:t,auditContext:y[G],mergeReceiptProof:g[G]}));jx({receiptOnlyIds:S,results:T,repair:w});let L=await qx({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),P=await Ua({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),M=p===0?o:await Ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),z=Zy(M),H=P.checks.every(G=>G.status==="ok"),J=n?u.length===0:L+f.length===u.length,ee=[w.totals.failed===0,H,J,z.count===0,!z.truncated].every(Boolean),Ee=a.truncated||z.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,Qe=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",Ee,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:ee?["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.",Ee,...i.length>0&&p===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(G=>G!==void 0);return{ok:ee,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:L,abandoned:f.length,summaries:u.map(nn),missing_history_references_before:a.count,legacy_disposition_eligible:i.length,legacy_disposition_recorded:p,missing_history_references_after:z.count},validation:P,guidance:Qe,generated_at:P.generated_at}}import{createHash as Kx}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3483e997-6bee-52bf-a048-8fe5c2427d06")}catch{}})();var rw=1,ow=/^[A-Za-z0-9_-]+$/,zx=100,tw=1e3;var OH=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Xe(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function Hx(e){return Kx("sha256").update(Yt({type:Xe(e.type),author:Xe(e.author),item:Xe(e.item),harness:Xe(e.harness),agent_instance:Xe(e.agentInstance),provenance:Xe(e.provenanceFilter)})).digest("hex").slice(0,24)}function nw(e,t){let n={version:rw,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function Bx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===rw,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function Vx(e,t){let n=e.trim();if(n.length===0||n.length>4096||!ow.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!Bx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function Wx(e){let t=e??zx;if(!Number.isSafeInteger(t)||t<0||t>tw)throw new l(`Mutation event limit must be an integer from 0 to ${tw}.`,d.USAGE,{code:"invalid_event_limit"});return t}function Yx(e,t){let n=e?.trim();if(!n)return{};if(ow.test(n))return{cursor:Vx(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function Jx(e,t){let n=await Ks(e,t);if(n===null){if(!await Tu(e))return{...await Cu(e,t),source:"authoritative_history"};n=await Ks(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function Xx(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Pi(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=Wx(e.limit),r=Xx(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let o=await A(t),a=o.agent_identity.identity_vocabulary,i=P_(o.agent_identity.harness_signals),s=N_({provenance:e.provenanceFilter},i),c=Xe(e.harness),m=Hx(e),{cursor:p,sinceTimestamp:u}=Yx(e.since,m),f={...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:Xe(e.type),authors:Xe(e.author),harnesses:c,harness_alias_authors:c?Object.entries(a.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:Xe(e.agentInstance),provenance:[...s].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:Xe(e.item),limit:n},_=await Jx(t,f),h=_.events.map(y=>({...r==="row"?{cursor:nw(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:L_(y.entry,a,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:nw(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:$_(_.events.map(y=>y.entry),a,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="015a3a52-f631-5ab7-b5c5-10a54a0b750c")}catch{}})();var Qx="1h",Zx="now",eP="+1d";function qt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function aw(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return Ie(n,r)}async function iw(e,t,n,r){let o=aw(e,t,n),a=[];return qt(a,"start",n.start??Zx),n.end!==void 0?qt(a,"end",n.end):qt(a,"duration",n.duration??Qx),qt(a,"location",n.location),qt(a,"timezone",n.timezone),n.allDay===!0&&qt(a,"all_day","true"),o.event=[a.join(",")],Gt(o,r)}function sw(e,t,n){return iw("Meeting",e,t,n)}function cw(e,t,n){return iw("Event",e,t,n)}function lw(e,t,n){let r=aw("Reminder",e,t),o=[];return qt(o,"at",t.at??eP),qt(o,"text",t.text??e),r.reminder=[o.join(",")],Gt(r,n)}import zr from"node:crypto";import{cp as dw,lstat as tP,mkdir as yn,readFile as Qn,readdir as ql,rename as uw,rm as zl,writeFile as Ni}from"node:fs/promises";import F from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3b4a5521-a665-5f60-8d01-16033b078916")}catch{}})();var fw="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var _w=F.join("runtime","workspace-snapshots"),nP=new Set(["checkpoints","locks","runtime","search","transactions"]),rP=/^[a-z0-9][a-z0-9._-]*$/,Kr="sdk-workspace-transaction",jl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},hw={renameEntry:uw,removeEntry:async e=>{await zl(e,{recursive:!0,force:!0})}},Kl=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Qn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Kr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ne(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
24
+ `)}};async function gw(e,t=""){let n=await ql(F.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((a,i)=>a.name.localeCompare(i.name))){if(t.length===0&&nP.has(o.name))continue;let a=F.posix.join(t.replaceAll(F.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${a}`);if(o.isDirectory())r.push(...await gw(e,a));else if(o.isFile())r.push(a);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${a}`)}return r}async function yw(e){let t=await gw(e),n=zr.createHash("sha256"),r=[],o=0;for(let i of t){let s=await Qn(F.join(e,i));r.push(s),o+=s.byteLength,n.update(i),n.update("\0"),n.update(String(s.byteLength)),n.update("\0"),n.update(s)}let a=n.digest("hex");return{manifest:{schema:fw,fingerprint:a,files:t,bytes:o},contents:r}}function mw(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
25
+ `).filter(t=>t.trim().length>0).length}async function oP(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),a=await Promise.all(o.map(async i=>[i,await Qn(F.join(e,i))]));for(let[i,s]of a)n.set(i,s)}return n}function Hl(e){if(!rP.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function ww(e,t){return or(`workspace_snapshot_${e}`,t,{codes:{capacity:jl.capacity.code,permission:jl.permission.code,resource:jl.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function wn(e){return F.join(e,_w)}function vw(e){return new l(`Unknown workspace snapshot: ${e}`,d.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function bw(e,t){try{return JSON.parse(await Qn(e,"utf8"))}catch(n){throw He(n)?vw(t):n}}async function pw(e,t,n){try{await zl(e,{recursive:n})}catch(r){throw He(r)?vw(t):r}}async function aP(e,t,n=hw){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function iP(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(a){throw await r.renameEntry(n,t),await r.removeEntry(e),a}await r.removeEntry(n)}async function sP(e,t){return Hl(t),/^[a-f0-9]{64}$/.test(t)?t:(await bw(F.join(wn(e),"refs",`${t}.json`),t)).fingerprint}async function Bl(e,t={}){if(t.name!==void 0&&(Hl(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await yw(e),o=wn(e),a=F.join(o,"objects",n.fingerprint),i=!1;try{i=(await tP(a)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&He(s)))throw s}if(!i){let s=F.join(o,"objects",`.create-${process.pid}-${zr.randomUUID()}`);await ww("create_object",async()=>{await yn(F.join(s,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let p=F.join(s,"files",m);await yn(F.dirname(p),{recursive:!0}),await Ni(p,r[c])}await Ni(F.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
26
+ `,"utf8"),await yn(F.dirname(a),{recursive:!0})}),i=await aP(s,a)}if(t.name!==void 0){let s={name:t.name,fingerprint:n.fingerprint},c=F.join(o,"refs");await yn(c,{recursive:!0});let m=F.join(c,`.ref-${process.pid}-${zr.randomUUID()}`);await Ni(m,`${JSON.stringify(s,null,2)}
27
+ `,"utf8"),await uw(m,F.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Hr(e,t){let n=await sP(e,t),r=await bw(F.join(wn(e),"objects",n,"manifest.json"),t);if(r.schema!==fw||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Vl(e){let t=wn(e),n=await ql(F.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&He(o))return[];throw o}),r=await ql(F.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&He(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Hr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Qn(F.join(t,"refs",o),"utf8"))))}}async function Wl(e,t){let n=await Hr(e,t),{manifest:r,contents:o}=await yw(e),a=new Map(r.files.map((u,f)=>[u,o[f]])),i=await oP(F.join(wn(e),"objects",n.fingerprint,"files"),n.files),s=new Set(r.files),c=new Set(n.files),m=new Set([...s,...c]);for(let u of m){let f=a.get(u),_=i.get(u);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(u)}let p=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let f=mw(a.get(u)),_=mw(i.get(u));return{path:u,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(u=>u.removed_entries>0).sort((u,f)=>u.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...s].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!s.has(u)).length,removed_item_count:[...s].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:p.length,removed_history_entry_count:p.reduce((u,f)=>u+f.removed_entries,0),affected_history_streams:p,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function kw(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,a=n.lockWaitMs??5e3,i=await Te(e,Kr,o,r,!1,!1,a),s=new Kl(uo(e,Kr),r,o);s.start(),await s.refreshNow();let c,m=!1,p=!1;try{let u=await Wl(e,t),f=await Hr(e,t),_=await Bl(e),h=f.fingerprint,y=wn(e),g=F.join(y,"objects",h,"files"),w=F.dirname(e),b=F.basename(e);c=F.join(w,`.${b}.restore-${zr.randomUUID()}`);let S=F.join(w,`.${b}.backup-${zr.randomUUID()}`);await ww("restore_stage",async()=>{await yn(c,{recursive:!0}),await dw(g,c,{recursive:!0,force:!1}),await yn(F.join(c,"runtime"),{recursive:!0}),await dw(y,F.join(c,_w),{recursive:!0,force:!1})});let T=await $u({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:a}),L=F.relative(c,T.historyPath).replaceAll("\\","/");await s.stop(),p=!0;let P=uo(c,Kr);return await yn(F.dirname(P),{recursive:!0}),await Ni(P,await Qn(uo(e,Kr)),{flag:"wx"}),m=!0,await iP(c,e,S,hw,async()=>{s.start(),p=!1,await s.refreshNow()}),await s.stop(),p=!0,{manifest:f,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:L,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!m&&await Promise.allSettled([zl(c,{recursive:!0,force:!0})]),u}finally{try{p||await s.stop()}catch{}finally{await i()}}}async function Sw(e,t){Hl(t);let n=wn(e);if(!/^[a-f0-9]{64}$/.test(t))return await pw(F.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Vl(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await pw(F.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f25e4f-09a1-554f-9e0b-a999fcce5c55")}catch{}})();function Br(e){let t={...e.args,...e.options};return Ie(e.options,t)}function kt(e,t){let n=v(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Zn(e){return typeof e=="string"?[e]:ge(e)}function Ew(e){return Yy(Br(e),e.global)}function Aw(e){let t=Br(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Pi({cwd:v(t,"cwd"),pmRoot:v(t,"path"),since:v(t,"since"),type:Zn(t.type),author:Zn(t.author),item:Zn(t.item),limit:t.limit===void 0?void 0:Me(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Zn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Zn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Zn(t.provenanceFilter)}})}function Tw(e){let t=Br(e),n=kt(t,"subcommand");if(n==="install")return wf({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return ew({dryRun:t.dryRun===!0,author:v(t,"author"),message:v(t,"message"),force:t.force===!0},e.global);if(n==="report")return m_({includeReconciled:t.includeReconciled===!0,cwd:v(t,"cwd")});if(n==="driver")return Xy({artifact:kt(t,"artifact"),basePath:kt(t,"basePath"),oursPath:kt(t,"oursPath"),theirsPath:kt(t,"theirsPath"),outputPath:v(t,"outputPath")??v(t,"output"),itemPath:v(t,"itemPath"),prefer:v(t,"prefer")},e.global);throw Ce({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Cw(e){let t=Br(e),n=kt(t,"subcommand");if(n==="position")return j_(e.global);if(n!=="snapshot")throw Ce({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=v(t,"snapshotAction")??kt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return Bl(o,{name:v(t,"name")});if(r==="list")return Vl(o);let a=kt(t,"target");if(r==="inspect")return Hr(o,a);if(r==="delete")return Sw(o,a);if(r==="restore")return t.dryRun===!0?Wl(o,a):kw(o,a,{force:t.force===!0,author:v(t,"author"),message:v(t,"message"),lockTtlSeconds:Me(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Me(t.lockWaitMs,"lockWaitMs")});throw Ce({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Li(e){let t=Br(e),n=kt(t,"title");return e.action==="meet"?sw(n,t,e.global):e.action==="event"?cw(n,t,e.global):lw(n,t,e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27bbfaed-a594-5b3b-84ba-431be02e002e")}catch{}})();function Iw(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:v(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ge(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:v(e,"measurementSource"),measurementItem:v(e,"measurementItem"),measurementRevision:v(e,"measurementRevision"),author:v(e,"author"),message:v(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:v(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import zP from"node:fs/promises";import Bw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function $i(e,t,n,r,o,a="min"){let i=o==="min"?e-t:t-e,s=a==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&s<0}function cP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,a=null,i=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let p;try{p=JSON.parse(m)}catch{continue}if(p===null||typeof p!="object"||!("ts"in p)||typeof p.ts!="string")continue;let u=p.ts,f=Date.parse(u);Number.isNaN(f)||($i(f,i,u,o,"min")&&(i=f,o=u),$i(f,s,u,a,"max","max")&&(s=f,a=u))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:a}}function Rw(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>cP(_,h)),a=0,i=0,s=null,c=null,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let _ of o){if(a+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);$i(h,m,_.id,s?.id??null,"min")&&(m=h,s={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);$i(h,p,_.id,c?.id??null,"max")&&(p=h,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:a,total_bytes:i,largest_by_bytes:u,deepest_by_lines:f,oldest_entry:s,newest_entry:c}}import{createHash as dP}from"node:crypto";import{execFile as mP}from"node:child_process";import Pw from"node:path";import{promisify as pP}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Ow=1;function lP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Yl(e){if(e===null)return{format_version:Ow,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Ow||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!lP(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var uP=pP(mP),fP=50,xw=1e3,_P=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Nw(e){let t=e.trim().toLowerCase();if(!_P.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function hP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Vr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function gP(e){let t=e??fP;if(!Number.isSafeInteger(t)||t<0||t>xw)throw new l(`Improvement observation limit must be an integer from 0 to ${xw}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Lw(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function yP(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Nw(n.metric),o=hP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let a=await vP(e,n.revision),i=Vr(n.source,"source"),s=Vr(n.itemId,"itemId"),c=Vr(n.unit,"unit"),m=Vr(n.idempotencyKey,"idempotencyKey")??(a.revision_source==="unversioned"?void 0:[a.revision,r,i??"manual",s??"workspace"].join(":")),p={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Lw(n.observedAt??k(),"observedAt"),...a,author:C(n.author,t.author_default),...s===void 0?{}:{item_id:s},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:dP("sha256").update(Yt(p)).digest("hex").slice(0,24),...p}}function wP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function vP(e,t){let n=Vr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await uP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Zd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function bP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function $w(e,t={}){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await yP(n,r,e),a=Pw.join(n,"improvement-ledger.json"),i=await aa({pmRoot:n,filePath:a,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:s=>{let c=Yl(s),m=wP(c,o);return m?{raw:s,result:m}:(c.observations.push(o),c.observations.sort((p,u)=>p.observed_at.localeCompare(u.observed_at)||p.metric.localeCompare(u.metric)||p.id.localeCompare(u.id)),{raw:`${Yt(c)}
28
+ `,result:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function Fw(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=e.metric===void 0?void 0:Nw(e.metric),r=e.since===void 0?void 0:Lw(e.since,"since"),o=gP(e.limit),a=Yl(await X(Pw.join(t,"improvement-ledger.json"))).observations.filter(s=>(n===void 0||s.metric===n)&&(e.itemId===void 0||s.item_id===e.itemId)&&(r===void 0||s.observed_at>=r)),i=new Map;for(let s of a){let c=i.get(s.metric)??[];c.push(s),i.set(s.metric,c)}return{observations:[...a].reverse().slice(0,o),total:a.length,truncated:a.length>o,trends:[...i].map(([,s])=>bP(s)).sort((s,c)=>s.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function Mw(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function kP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function SP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Jl(e=pr,t=xn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function EP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Xl(e,t=xn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let a of t){let i=`${o.agent_harness}\0${a}`,s=r.get(i)??{harness:o.agent_harness,dimension:a,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1;let c=o.agent_provenance?.[a];c!=null&&c.value.length>0?s.observed+=1:c===null?s.unavailable+=1:s.legacy_missing+=1,r.set(i,s)}return[...r.values()].map(o=>{let a=o.observed+o.unavailable;return{...o,coverage:a===0?null:o.observed/a,inert:a>=n&&o.observed===0}}).sort((o,a)=>o.harness.localeCompare(a.harness)||o.dimension.localeCompare(a.dimension))}function AP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let p=`${c.agent_harness}\0${m}`,u=o.get(p)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),o.set(p,u)}let a=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[p])=>m.localeCompare(p)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=a.filter(c=>c.entries>=r),s=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&s.length===0,minimum_coverage:n,minimum_entries:r,rows:a,failures:s}}function TP(e){let t=[...e].sort((a,i)=>a.ts.localeCompare(i.ts)||a.author.localeCompare(i.author)||a.op.localeCompare(i.op)||a.before_hash.localeCompare(i.before_hash)||a.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let a of t){let i=a.agent_episode,s=Mw(a),c=`${s.source}:${s.id}`,m=n.get(c);if(m){m.entries.push(a);continue}let p={id:s.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:s.source,entries:[a],children:[]};n.set(c,p),i!==void 0&&r.set(s.id,p)}let o=[];for(let a of n.values()){let i=a.parent_id?r.get(a.parent_id):void 0;i&&kP(a,i,r)?i.children.push(a):o.push(a)}return SP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var CP=1e4,Dw=1e5,IP=1e3,RP=30,OP=["append","comment","docs","file","learning","note","test_run"];function xP(e){let t=e??CP;if(!Number.isSafeInteger(t)||t<1||t>Dw)throw new l(`History analytics event limit must be an integer from 1 to ${Dw}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function Uw(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function PP(e){let t=e?.trim();if(!t)return new Date(Date.now()-RP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),a=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*a).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Gw(e,t){let n=xP(t.eventLimit),r=PP(t.since),o=[],a=r,i=!1;for(;o.length<n;){let s=await Pi({pmRoot:e,since:a,limit:Math.min(IP,n-o.length),full:!0}),c=s.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),i=s.has_more,a=s.next_cursor,!s.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:a}:{},source:"history_event_index"}}}function NP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function LP(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function $P(e){return OP.some(t=>e.startsWith(t))}function jw(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function FP(e,t,n){let r=new Map,o=new Map,a=new Map;for(let i of t){let s=NP(i.entry,e),c=LP(i.entry),m=o.get(i.item_id)===!0,p=c===void 0?m:n.has(c);if(c!==void 0&&o.set(i.item_id,p),!s)continue;let u=jw(r,s);u.events+=1,$P(i.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!m&&p?(u.closes+=1,a.set(i.item_id,s)):c!==void 0&&m&&!p&&(u.reopens+=1)}return{buckets:r,lastCloseValue:a}}function MP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(a=>a.kind==="discovered_from").map(a=>a.id));for(let a of o){let i=t.get(a);i&&(jw(e,i).defectEscapes+=1)}}}function DP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function UP(e,t,n,r,o,a){let{buckets:i,lastCloseValue:s}=FP(e,t,r);return MP(i,s,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>DP(c,m,o,a)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function GP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),a=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(a)?1:Math.max(1,(a-o)/864e5)}function jP(e,t,n){let r=Jl(t),o=Xl(e,xn,n),a=o.filter(s=>s.inert).map(s=>({harness:s.harness,dimension:s.dimension,explicit_samples:s.observed+s.unavailable})),i=r.filter(s=>!s.covered).map(s=>s.dimension);return{descriptors:r,observations:o,inert:a,undeclared:i,warnings:[...a.map(s=>`provenance_dimension_inert:${s.harness}:${s.dimension}:${String(s.explicit_samples)}`),...i.map(s=>`provenance_dimension_undeclared:${s}`)]}}function qw(e,t=pr,n={}){let r=Uw(n.minimumSample);return{...jP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function Kw(e,t,n,r={}){let o=Uw(r.minimumSample),a=GP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>UP(i,e.events,t,n,o,a)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var qP=32;function KP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let a=o.slice(0,o.indexOf("=")).trim();r.length>0&&a!=="unit"&&a!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Wr(e,t){let n=KP(e).map(r=>{let[o,...a]=r.split(","),i=o.indexOf("="),s=o.slice(0,i).trim(),c=o.slice(i+1).trim(),m=Number(c);if(i<=0||s.length===0||c.length===0||!Number.isFinite(m))throw new l(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,u;for(let f of a){let _=f.indexOf("="),h=f.slice(0,_).trim(),y=f.slice(_+1).trim();if(h==="unit"&&y.length>0)p=y;else if(h==="threshold"&&y.length>0&&Number.isFinite(Number(y)))u=Number(y);else throw new l(`Invalid --measure attribute "${f}"`,d.USAGE)}return{name:s,value:m,unit:p,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,qP)}function zw(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Hw(e,t){let n=e.flatMap(a=>a.measurements??[]).filter(a=>a.name===t).sort((a,i)=>i.recorded_at.localeCompare(a.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function HP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function BP(e,t,n,r,o){let a=wr(e,"type",r),i=new Set(a.rows.map(u=>u.key)),s=t.filter(u=>!i.has(u)),c=(o?[...a.rows,...s.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:a.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),m=HP([...n]);for(let u of e)m[u.status]+=1;let p=Object.fromEntries(Object.entries(m).filter(([,u])=>o||u>0));return{byType:c,byStatus:p,omitted:o?0:s.length+Object.values(m).filter(u=>u===0).length}}function VP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function WP(e){let t=Bw.join(e,"history");if(!await j(t))return[];await Rn({path:t,scope:"project"});let n=(await zP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,a)=>o.localeCompare(a)),r=[];for(let o of n){let a=Bw.join(t,o),i=await X(a);i!==null&&(await Rn({path:a,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function YP(e,t){let n=[],r=k();for(let o of Wr(t.observe,r))n.push(await $w({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function JP(e,t,n){let r={};return t.byAssignee&&(r.assignee=wr(e,"assignee",n)),t.byTag&&(r.tag=wr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=wr(e,"priority",n)),r}async function XP(e,t,n,r,o){let a={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await Gw(e,a):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?qw(i,n.agent_identity?.harness_signals,a):void 0,fleetAttribution:o.fleetAttribution&&i?Kw(i,t,r,a):void 0}}function QP(e,t,n,r,o){let a=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...a?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Ql(e,t={}){let n=E(process.cwd(),e.path);await I(n);let r=await A(n),o=await YP(e,t),a=x(r,O()),i=$(r.schema),s=t.fieldUtilization?await Qu(n,r.item_format,a.type_to_folder,void 0,r.schema):await fe(n,r.item_format,a.type_to_folder,void 0,r.schema);await zu({pmRoot:n,settings:r,itemIds:s.map(S=>S.id),commandLabel:"stats"});let c=Sa(i),m=BP(s,a.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),p=await WP(n),u=0;for(let S of p)u+=VP(S.raw);let f=t.storage?Rw(p):void 0,_=t.metadataCoverage?sf(s,c):void 0,h=JP(s,t,c),y=t.fieldUtilization?cf(s):void 0,g=t.measurements===!0||o.length>0?await Fw({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:b}=await XP(n,s,r,i.terminal_statuses,t);return QP({items:s.length,history_streams:p.length,history_entries:u},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:o,provenanceCoverage:w,fleetAttribution:b})}import ZP from"node:fs/promises";import Kt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a41eaff2-6a15-5e82-b3aa-03ca48fc3eb5")}catch{}})();var Qw=Kt.join("runtime","telemetry","events.jsonl"),Zw=Kt.join("runtime","telemetry","state.json"),eN=Kt.join("runtime","telemetry"),tN=20,ev=Jt.filter(e=>e.lifecycle==="deprecated"),Vw=["status","flush","stats","clear"],Ww=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Zl=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Yw=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},nN=e=>({command:Zl(e.event.command,"<unknown>"),eventType:Zl(e.event.event_type,"unknown"),eventSchemaVersion:Yw(e.event.schema_version),clientSchemaVersion:Yw(e.client_schema_version)}),rN=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),oN=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},aN=e=>{let t=e?.command_resolution;return Zl(t,"")||void 0},tv=(e,t)=>{e[t]=(e[t]??0)+1},iN=(e,t)=>{let n=oN(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=aN(t);r!==void 0&&tv(e.resolution_counts,r)},sN=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Jw=(e,t)=>{t!==void 0&&e.add(t)},cN=(e,t)=>{let n=nN(t),r=e.get(n.command)??rN();r.count+=1,r.max_attempts=Math.max(r.max_attempts,sN(t.attempts)),tv(r.event_type_counts,n.eventType),Jw(r.event_schema_versions,n.eventSchemaVersion),Jw(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&iN(r,t.event.payload),e.set(n.command,r)},lN=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((a,i)=>a-i),o=Object.entries(t.resolution_counts).sort((a,i)=>a[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((a,i)=>a[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((a,i)=>a-i),client_schema_versions:[...t.client_schema_versions].sort((a,i)=>a-i),...r.length>0?{duration_p50_ms:Ww(r,.5),duration_p95_ms:Ww(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},dN=e=>{let t=(e??"status").trim().toLowerCase();if(Vw.includes(t))return t;throw Ce({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Vw,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},td=()=>{throw new l("--limit must be a positive integer",d.USAGE)},nv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?td():e,mN=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?td():nv(Number.parseInt(t,10))},pN=e=>e===void 0?tN:typeof e=="number"?nv(e):typeof e=="string"?mN(e):td(),uN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},fN=e=>{try{let t=JSON.parse(e);return uN(t)?t:void 0}catch{return}},_N=e=>e===null?[]:e.split(`
29
+ `).map(t=>t.trim()).filter(t=>t.length>0),rv=e=>{let t=_N(e),n=[],r=0;for(let o of t){let a=fN(o);a===void 0?r+=1:n.push(a)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},hN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gN=e=>{try{let t=JSON.parse(e);return hN(t)?t:{}}catch{return{}}},ed=async e=>{let t=await X(e);return t===null||t.trim().length===0?{}:gN(t)};function yN(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function wN(e,t,n){let r=Object.create(null);for(let[o,a]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof a!="object"||a===null||Array.isArray(a))continue;let i=a;!Number.isSafeInteger(i.count)||i.count<1||typeof i.last_seen!="string"||!i.last_seen.startsWith(o)||(r[o]={count:i.count,last_seen:i.last_seen})}return r}function Xw(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let a of ev){let i=r[a.alias];if(typeof i!="object"||i===null||Array.isArray(i))continue;let s=i;if(s.canonical!==a.canonical||typeof s.days!="object"||s.days===null||Array.isArray(s.days))continue;let c=wN(s.days,t,o);Object.keys(c).length>0&&(n[a.alias]={canonical:a.canonical,days:c})}return n}async function vN(e,t,n){let r=yN(n),o=await ed(t),a=Xw(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(a))return a;try{await tc(async()=>{let i=await ed(t);if(i.alias_usage===void 0)return;let s=Xw(i.alias_usage,r);JSON.stringify(i.alias_usage)!==JSON.stringify(s)&&await ne(t,`${JSON.stringify({...i,alias_usage:s},null,2)}
30
+ `)},e,250)}catch{}return a}var Fi=e=>e??null,Mi=async e=>{let t=await A(e),n=Kt.join(e,Qw),r=Kt.join(e,Zw),o=await X(n),a=rv(o),i=await ed(r),s=tf();return{enabled:t.telemetry.enabled&&!s.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:s,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:a.rows_total,queue_entries:a.valid_entries,queue_invalid_rows:a.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:Fi(i.last_attempted_flush_at),last_successful_flush_at:Fi(i.last_successful_flush_at),last_failed_flush_at:Fi(i.last_failed_flush_at),last_failed_flush_error:Fi(i.last_failed_flush_error)}},bN=e=>{let t=new Map;for(let n of e)cN(t,n);return[...t.entries()].map(([n,r])=>lN(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},kN=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Mi(t.globalPmRoot),generated_at:k()}),SN=async(e,t)=>{let n=await Mi(t.globalPmRoot);await of(t.globalPmRoot);let r=await Mi(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),a=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:a,queue_drained:a,status:r,generated_at:k()}},EN=async(e,t)=>{let n=pN(e.limit),r=await X(t.queuePath),o=rv(r),a=bN(o.entries),i=a.slice(0,n),s=await A(t.globalPmRoot),c=await vN(t.globalPmRoot,t.statePath,s.telemetry.retention_days),m=Object.entries(c).map(([p,u])=>{let f=Object.values(u.days);return{alias:p,canonical:u.canonical,count:f.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:f.map(_=>_.last_seen).sort().at(-1)}}).sort((p,u)=>u.count-p.count||p.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:a.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:a.length>i.length,stats:i,alias_usage:m,zero_use_aliases:ev.map(p=>p.alias).filter(p=>c[p]===void 0),alias_usage_retention_days:s.telemetry.retention_days,generated_at:k()}},AN=async(e,t)=>tc(async()=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Fe(t.globalPmRoot,n,"telemetry:clear");let o=Kt.join(t.globalPmRoot,eN),a=await j(o);return await ZP.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:a&&!await j(o),queue_exists_after:await j(t.queuePath),state_exists_after:await j(t.statePath),status:await Mi(t.globalPmRoot),generated_at:k()}},t.globalPmRoot),TN={status:kN,flush:SN,stats:EN,clear:AN};async function ov(e,t){let n=dN(e.subcommand),r=lt(process.cwd());return TN[n](e,{globalPmRoot:r,queuePath:Kt.join(r,Qw),statePath:Kt.join(r,Zw)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var av=20;function CN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return av;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?av:t}function nd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let a=Xo(r.recorded_at,o.recorded_at);if(a!==0)return a;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=CN();return t.length>n?t.slice(t.length-n):t}async function Di(e){await ce({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=nd([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function iv(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function rd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=iv(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let a of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof a=="number"&&(!Array.isArray(o)||a>=o.length))return{found:!1,value:void 0};let i=Object.getOwnPropertyDescriptor(o,a);if(!i||!Object.hasOwn(i,"value"))return{found:!1,value:void 0};o=i.value}return{found:!0,value:o}}import{cp as IN,lstat as RN,mkdir as ON,readlink as xN,realpath as ad,stat as PN,symlink as sv}from"node:fs/promises";import K from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d27093d8-5bac-5dcf-8334-07c8b8bc93a7")}catch{}})();var NN=new Set([".agents",".git",".nyc_output",".turbo","coverage"]);function od(e){return e.split(K.sep).some(t=>NN.has(t.toLowerCase()))}function Yr(e){return e===".."||e.startsWith(`..${K.sep}`)||K.isAbsolute(e)}async function cv(e){try{return await PN(e)}catch(t){if(!He(t))throw t;return}}async function Ui(e){let t=[],n=e;for(;K.dirname(n)!==n;)try{return K.join(await ad(n),...t)}catch(r){if(!He(r))throw r;t.unshift(K.basename(n)),n=K.dirname(n)}return K.join(await ad(n),...t)}async function LN(e,t,n){let r=K.relative(t,await Ui(e));if(!Yr(r))return r;let o=[],a=e;for(;K.dirname(a)!==a;){let i=await Ui(a),s=n.find(([,c])=>c===i);if(s)return K.join(s[0],...o);o.unshift(K.basename(a)),a=K.dirname(a)}return r}async function lv(e,t){let n=[],r=[],o=await ad(e),a=await Ui(K.resolve(t));if(![K.relative(o,a),K.relative(a,o)].every(Yr))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await ON(K.dirname(t),{recursive:!0}),await IN(o,t,{recursive:!0,force:!0,async filter(i){let s=K.relative(o,i);if(!s)return!0;if(od(s))return!1;if(K.basename(i).toLowerCase()==="node_modules"){if((await cv(i))?.isDirectory()){let c=await Ui(i),m=K.relative(o,c);if(!Yr(K.relative(c,o))||!Yr(m)&&(od(m)||!m.split(K.sep).some(p=>p.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${s}`);n.push([s,c])}return!1}return(await RN(i)).isSymbolicLink()?(r.push([s,K.resolve(K.dirname(i),await xN(i)),(await cv(i))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[i]of n)await sv(K.resolve(o,i),K.join(t,i),"junction");for(let[i,s,c]of r){let m=await LN(s,o,n);if(Yr(m)||od(m))throw new Error(`Source symlink must target included workspace source: ${i}`);await sv(K.resolve(t,m),K.join(t,i),c)}}import{spawn as Iv}from"node:child_process";import{cp as uv,mkdir as md,mkdtemp as Rv,open as cd,readdir as ld,rm as Xr,symlink as DN}from"node:fs/promises";import{tmpdir as Ov}from"node:os";import ae from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var dv=100;function id(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function $N(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=dv?t:`${t.slice(0,dv-3)}...`}function mv(e){return e.map((t,n)=>`${n+1}. ${$N(t)}`).join("; ")}function FN(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function MN(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function pv(e,t){let n=FN(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,a)=>a+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let a=[],i=[];for(let s=0;s<e.length;s+=1)MN(e[s],o)&&(i.push(e[s]),a.push(s+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${mv(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:a,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=id(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${mv(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ae567115-9f40-5b3d-872d-73d1d543bc04")}catch{}})();var qi=20*1024*1024,UN=3e3,GN=1e4,jN=5e3,fv=120,qN=new Set(["locks","extensions","runtime"]),KN=new Set(["history","index","search","extensions","locks","runtime"]),zN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],HN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,BN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,VN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function pd(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function WN(){return pd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",UN)}function YN(){return pd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",GN)}function JN(){return pd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",jN)}function XN(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function QN(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function ud(e){let t=0,n=0,r=0,o=0;for(let a of e){let i=a.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function ZN(e){let t=e??"project";if(!ct.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function Ki(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(cn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${cn.join(", ")}`,d.USAGE)}function eL(e){return dn(e??"source","--workspace-context")}function xv(e,t,n){return n?t:dn(e.workspace_context_mode,"linked test")??t}function Pv(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ki(e.pm_context_mode)}function Nv(e,t){return e==="auto"?t?"tracker":"schema":e}function tL(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function nL(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function rL(e,t){let n={};if(!e)return n;for(let r of e){let o=Fr(r,t);if(o)for(let[a,i]of Object.entries(o))n[a]=i}return n}function oL(e,t){if(!e)return[];let n=[];for(let r of e){let o=Mr(r,t);o&&n.push(...o)}return[...new Set(n)]}function aL(e){let t=zi(e);return Tr(t).some(n=>dc(n)!==null)}function Lv(e){let t=zi(e);return Tr(t).some(n=>{let r=dc(n);if(!r)return!1;let o=E_(r);return o?VN.has(o.subcommand):!1})}function Gi(e){if(e)return b_.has(e.subcommand)?Kn(e.args,k_)?.subcommand:e.subcommand}function _v(e,t){if(e==="npx"||e==="bunx")return Da(t)?.command;if(e==="pnpm")return Gi(Kn(t,g_));if(e==="npm")return Gi(Kn(t,y_));if(e==="yarn")return Gi(Kn(t,w_));if(e==="bun")return Gi(Kn(t,v_))}function ji(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function sd(e){return!e||!pc(e.command)&&!S_(e.command)?!1:Ma(e.args)==="test-all"}var $v=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),iL=new Set(["npx","bunx"]);function Fv(e){let t=e.split(" ").filter(i=>i.length>0),n=mc(t);if(n.length===0)return!1;let[r,...o]=n,a=$v.get(r);if(a){let i=o.findIndex(s=>a.test(s));return i>=0?Fv(o.slice(i+1).join(" ")):!1}return pc(r)||uc(r)?Ma(o)==="test-all":r==="node"&&o.length>0&&uc(o[0])?Ma(o.slice(1))==="test-all":iL.has(r)?sd(Da(o)):r==="pnpm"?sd(fc(o)):r==="npm"?sd(_c(o)):!1}function Mv(e){let t=zi(e);return Tr(t).some(n=>Fv(n))}function Dv(e){if(Mv(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function zi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Uv(e){let t=e.split(" ").filter(i=>i.length>0),n=mc(t);if(n.length===0)return!1;let[r,...o]=n,a=$v.get(r);if(a){let i=o.findIndex(s=>a.test(s));return i>=0&&Uv(o.slice(i+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?sL(o):cL(r,o)}function sL(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function cL(e,t){return e==="npx"||e==="bunx"?ji(Da(t)?.command):e==="pnpm"||e==="npm"?ji((e==="pnpm"?fc(t):_c(t))?.command)||ji(_v(e,t)):(e==="yarn"||e==="bun")&&ji(_v(e,t))}function lL(e){if(Mv(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function dL(e){return e?e.map(mL):[]}function mL(e){let t=e.trim(),n=wg(t)?oi(de(e,"--add"),"--add"):{command:t},r=he(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Dv(r),{command:r,path:he(n.path),scope:ZN(n.scope),timeout_seconds:pL(he(n.timeout_seconds),he(n.timeout)),pm_context_mode:li(he(n.pm_context_mode),"--add"),workspace_context_mode:dn(he(n.workspace_context_mode),"--add"),env_set:Fr(he(n.env_set),"--add"),env_clear:Mr(he(n.env_clear),"--add"),shared_host_safe:ci(he(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:mn(he(n.assert_stdout_contains)),assert_stdout_regex:Vn(he(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:mn(he(n.assert_stderr_contains)),assert_stderr_regex:Vn(he(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:di(he(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:mi(he(n.assert_json_field_equals),"--add"),assert_json_field_gte:pi(he(n.assert_json_field_gte),"--add"),note:he(n.note)}}function he(e){let t=e?.trim();return t&&t.length>0?t:void 0}function pL(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ue(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function uL(e){return e?e.flatMap(t=>{let n=kg(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);Dv(o)}return n}):[]}function fL(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=de(n,"--remove"),a=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:a,value:i.trim()}}return{kind:"either",value:n}}):[]}function _L(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function hL(e){try{e.stdin?.end()}catch{}}function Gv(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=fv?t:`${t.slice(0,fv-3)}...`}function jv(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function dd(e){try{process.stderr.write(`${e}
31
+ `)}catch{}}function gL(e,t){if(!jv(t))return null;let n=Gv(e.command),r=Date.now();dd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let a=Date.now()-r;dd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${a} command="${n}"`)},YN());return o.unref?.(),o}function yL(e,t,n,r){if(!jv(r))return;let o=Gv(e.command),a=Date.now()-n,i=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",s=[];t.timedOut&&s.push("reason=timeout"),t.maxBufferExceeded&&s.push("reason=max_buffer"),t.outputTruncated&&s.push("output=truncated"),t.signal&&s.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),m=s.length>0?` ${s.join(" ")}`:"";dd(`[pm test] linked-test ${e.index}/${e.total} end status=${i} exit_code=${c} elapsed_ms=${a}${m} command="${o}"`)}async function hv(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Iv("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function wL(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function vL(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await hv(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{hv(r)},WN()),t.forceKillTimer.unref?.()}}function bL(e){return new Promise(t=>{let n=!1,r=null,o=(a,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(a))};e.on("exit",(a,i)=>{n||(r=setTimeout(()=>{o({code:a,signal:i},!0)},JN()),r.unref?.())}),e.on("close",(a,i)=>{o({code:a,signal:i})})})}function kL(e,t,n,r,o){return Iv(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function gv(e){let t=await cd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,qi),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>qi}}finally{await t.close()}}async function SL(e,t,n,r,o,a=process.cwd()){let i=Date.now(),s=await Rv(ae.join(Ov(),"pm-linked-test-output-"));try{let c=ae.join(s,"stdout.log"),m=ae.join(s,"stderr.log"),[p,u]=await Promise.all([cd(c,"w"),cd(m,"w")]),f;try{f=kL(e,n,p.fd,u.fd,a)}catch(H){throw await Promise.all([p.close(),u.close()]),H}let _=bL(f),h;f.on("error",H=>{h=H.message}),await Promise.all([p.close(),u.close()]),hL(f);let y={heartbeat:gL(r,o),forceKillTimer:null,timedOutTimer:null},g=vL(f,y),w=!1;y.timedOutTimer=setTimeout(()=>{w=!0,g()},t),y.timedOutTimer.unref?.();let{code:b,signal:S}=await _;wL(y);let[T,L]=await Promise.all([gv(c),gv(m)]),P=T.truncated||L.truncated,M=P?`
31
32
  [pm linked-test output truncated at ${qi} bytes per stream; the child process continued to completion]
32
- `:"",z={stdout:`${T.text}${M}`,stderr:L.text,exitCode:b,signal:S,timedOut:w,maxBufferExceeded:!1,outputTruncated:P,spawnError:h};return gL(r,z,i,o),z}finally{await Xr(s,{recursive:!0,force:!0})}}function SL(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${qi} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function EL(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
33
- `);return KN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>zN.test(n)&&HN.test(n))}function AL(e){return EL(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function TL(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Hi(e){let t=TL();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function gv(e,t){for(let[n,r]of Object.entries(t.env_set))ln.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)ln.has(n.toUpperCase())||delete e[n]}function CL(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function IL(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function RL(e,t,n){return{env_set:nL(e,"--env-set"),env_clear:rL(t,"--env-clear"),shared_host_safe:n===!0}}async function tr(e,t,n=!1,r=dd){if(await j(e))try{await ar("seed_linked_test",async()=>{if(await r(ae.dirname(t),{recursive:!0}),n){await pv(e,t,{recursive:!0,force:!0});return}await pv(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&He(o))return;throw o}}async function yv(e,t,n){await tr(re(n.projectPmRoot),re(e)),await tr(ae.join(n.projectPmRoot,"extensions"),ae.join(e,"extensions"),!0),await tr(re(n.globalPmRoot),re(t)),await tr(ae.join(n.globalPmRoot,"extensions"),ae.join(t,"extensions"),!0)}async function wv(e,t){if(!await j(e))return;let n=await cd(e,{withFileTypes:!0});for(let r of n){if(jN.has(r.name))continue;let o=ae.join(e,r.name),a=ae.join(t,r.name);if(r.isDirectory()){await tr(o,a,!0);continue}r.isFile()&&await tr(o,a)}}async function vv(e,t){let n=await ee(re(e));if(n===null||await j(Bs(e)))return;let r=await A(t);await Xr(Bs(t),{force:!0}),await Xr(re(t),{force:!0}),await ot({pmRoot:t,filePath:re(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function er(e){if(!await j(e))return 0;let t=0,n=await cd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||qN.has(r.name))continue;let o=ae.join(e,r.name),a;try{a=await cd(o,{withFileTypes:!0})}catch{continue}for(let i of a)i.isFile()&&Xd.some(s=>i.name.toLowerCase().endsWith(s))&&(t+=1)}return t}function OL(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function xL(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function PL(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?qe(e,t):Object.is(e,t)}function NL(e,t,n){let r=[];r.push(...bv("stdout",t,e.assert_stdout_contains)),r.push(...kv("stdout",t,e.assert_stdout_regex)),r.push(...bv("stderr",n,e.assert_stderr_contains)),r.push(...kv("stderr",n,e.assert_stderr_regex)),r.push(...LL(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},a=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(a).length>0))return r;let i;try{i=JSON.parse(t)}catch(s){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${s instanceof Error?s.message:String(s)}`),r}for(let[s,c]of Object.entries(o)){let m=nd(i,s);if(!m.found){r.push(`assert_json_field_equals missing path "${s}"`);continue}let p=xL(c);PL(m.value,p)||r.push(`assert_json_field_equals mismatch at "${s}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(m.value)})`)}for(let[s,c]of Object.entries(a)){let m=nd(i,s);if(!m.found){r.push(`assert_json_field_gte missing path "${s}"`);continue}if(typeof m.value!="number"||!Number.isFinite(m.value)){r.push(`assert_json_field_gte path "${s}" resolved to non-numeric value`);continue}m.value<c&&r.push(`assert_json_field_gte failed at "${s}" (expected >= ${c}, actual ${m.value})`)}return r}function bv(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function kv(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(a){r.push(`${e} regex assertion is invalid: /${o}/ (${a instanceof Error?a.message:String(a)})`)}return r}function LL(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var $L=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],FL=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function ML(e,t){let n=`${e}
34
- ${t}`;for(let r of $L)if(r.regex.test(n))return{code:r.code};return null}function DL(e,t){let n=`${e}
35
- ${t}`;return FL.some(r=>r.test(n))}function Sv(e){let t=zi(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Cr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&Dv(n))}function UL(e){return{root:e,schemaProjectPmPath:ae.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:ae.join(e,"schema","global"),trackerProjectPmPath:ae.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:ae.join(e,"tracker","global"),workspaceSnapshotRoot:ae.join(e,"workspace","project"),workspaceIsolatedRoot:ae.join(e,"workspace","isolated")}}function GL(e,t,n){return e.some(r=>Ov(r,t,n)==="snapshot")}async function jL(e,t){let n=ae.join(e,".agents"),r=ae.join(n,"pm");await dd(n,{recursive:!0}),await Xr(r,{recursive:!0,force:!0}),await MN(t,r,process.platform==="win32"?"junction":"dir")}async function qL(e,t=Nr,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function KL(e,t,n){t&&(await yv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await yv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await wv(t.projectPmRoot,e.trackerProjectPmPath),await wv(t.globalPmRoot,e.trackerGlobalPmPath),await vv(t.projectPmRoot,e.trackerProjectPmPath),await vv(t.globalPmRoot,e.trackerGlobalPmPath)))}function zL(e,t,n){return e.some(r=>{let o=r.command??"",a=o.length>0&&Nv(o),i=n?.autoPmContext===!0&&a?"auto":xv(r,t,n?.overrideLinkedPmContext===!0);return Pv(i,a)==="tracker"})}async function HL(e,t){return{sourceProjectItemCount:t?await er(t.projectPmRoot):0,sourceGlobalItemCount:t?await er(t.globalPmRoot):0,schemaProjectItemCount:await er(e.schemaProjectPmPath),schemaGlobalItemCount:await er(e.schemaGlobalPmPath),trackerProjectItemCount:await er(e.trackerProjectPmPath),trackerGlobalItemCount:await er(e.trackerGlobalPmPath)}}function BL(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,a=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,s=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:a,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==a),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:s,trust:e.trust}}async function VL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ki(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?oL(n):!1,o=r&&n?Nv(n):!1,a=e.options?.autoPmContext===!0&&o,i=a?"auto":xv(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),s=Pv(i,o),c=s==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await jL(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await fc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await fc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:BL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:s,autoPmContextApplied:a,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Ev(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Qr(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function WL(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function YL(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return WL(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function JL(e){if(!e.linkedTest.command)return Ev(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=cL(e.linkedTest.command);return t?Ev(e.linkedTest,e.executionContext,t):null}function XL(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Qr(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Qr(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function QL(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=tL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Qr(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function ZL(e){return JL(e)||YL(e)||XL(e)||QL(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!eL(e.linkedTest)?Qr(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function e$(e){let t=IL(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return gv(n,e.runtimeDirectives),gv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&CL(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Er]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Er]="read_only"),n}function t$(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function Av(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function n$(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:OL(e.execution),failure_category:AL(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:SL(e.execution,e.timeoutMs)}}function r$(e){if(e.options?.failOnEmptyTestRun===!0||Sv(e.linkedTest.command??"")){let n=ML(e.execution.stdout,e.execution.stderr);if(n)return Av({...e,emptyRunSignal:n});if(Sv(e.linkedTest.command??"")&&!DL(e.execution.stdout,e.execution.stderr))return Av({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=NL(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Qr(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):t$(e.linkedTest,e.executionContext,e.execution)}async function o$(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await kL(t,n,e$(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?r$({...e,execution:r}):n$({...e,execution:r,timeoutMs:n})}async function ud(e,t,n){let r=[],o=await Iv(ae.join(Rv(),"pm-linked-test-")),a=UL(o),i=Ki(n?.pmContext),s=ZN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=RL(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,u=E_(),f=zL(e,i,n),_=GL(e,s,n?.overrideLinkedWorkspaceContext===!0),h=await S_(u);try{await qL(a,Nr,f),await dd(a.workspaceIsolatedRoot,{recursive:!0}),await KL(a,p,f),_&&await cv(u,a.workspaceSnapshotRoot);let y=await HL(a,p);for(let g=0;g<e.length;g+=1){let w=e[g],b=Ov(w,s,n?.overrideLinkedWorkspaceContext===!0),S=await VL({linkedTest:w,layout:a,counts:y,sourceRoots:p,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:s,workspaceContextMode:b,currentSourceRef:h,sourceWorkspaceRoot:u}),T=ZL({linkedTest:w,executionContext:S.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await o$({linkedTest:w,index:g,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Xr(a.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function a$(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,a=await q(n,t,r.id_prefix,r.item_format,o);if(!a)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await se(a,{schema:r.schema});return{itemId:a.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function i$(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function s$(e,t){let n=[...e];for(let r of t)n.some(o=>i$(o,r))||n.push(r);return n}function c$(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((a,i)=>r.has(i+1)?!1:!t.some(s=>s.kind==="command"?a.command===s.value:s.kind==="path"?a.path===s.value:a.command===s.value||a.path===s.value));return{tests:o,removed:e.length-o.length}}function l$(e,t,n,r){return c$(s$(e,t),n,r)}function d$(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function m$(e){if(d$(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function p$(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:a,adds:i,removes:s,removeIndexes:c}=e;if(i.length===0&&s.length===0&&c.length===0)return a$({id:t,pmRoot:r,settings:o,typeToFolder:a});let m=0,p=await ce({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let f=u.metadata.tests??[],_=l$(f,i,s,c);if(m=_.removed,(s.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...s.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=_.tests,{changedFields:qe(f,_.tests)?[]:["tests"]}}});return{itemId:p.item.id,tests:p.item.tests??[],testRuns:p.item.test_runs??[],changed:p.changedFields.length>0,removed:m}}function u$(e,t){m$(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ad(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?mv(t,n):void 0,o=e.timeout===void 0?void 0:ue(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:Ki(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function f$(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await ud(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:lt(process.cwd())}})}function _$(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=pd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function h$(e){let t=XN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),a=Yr(e.options.measure,o);return{run_id:JN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:a.length>0?a:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function g$(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:a,runResults:i,failOnSkippedTriggered:s,warnings:c}=e;if(t.run!==!0||!a)return;let m=h$({options:t,runStartedAt:a,runResults:i,failOnSkippedTriggered:s});if(r.testing.record_results_to_items!==!0)return{entry:m,receipt:{recorded:!1,reason:"tracking_disabled",run_id:m.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Di({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),{entry:m,receipt:{recorded:!0,reason:"recorded",run_id:m.run_id}}}catch(p){return c.push(`test_result_tracking_failed:${o}:${p instanceof Error?p.message:String(p)}`),{entry:m,receipt:{recorded:!1,reason:"write_failed",run_id:m.run_id}}}}function Tv(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),a=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),s=Number(i);if(o<=0||a.length===0||i.length===0||!Number.isFinite(s))throw new l("--metric-below must use name=value",d.USAGE);r=Kw(t,a,s)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:zw(t,e.metricDiff)}}async function y$(e,t,n){if(e.acknowledgeLinkedTests===!0)return A_(t,n,k())}function w$(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:a,warnings:i,recording:s,measurementProjection:c}=e;return{ok:n.every(m=>m.status!=="failed")&&a!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:r,selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count}:void 0,fail_on_skipped_triggered:a?!0:void 0,warnings:i.length>0?i:void 0,changed:t.changed||s?.receipt.recorded===!0,...s?{evidence_recording:s.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Bi(e,t,n){let r=Nt(),o=E(process.cwd(),n.path);await I(o);let a=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Yr(t.measure,"validation"),Tv(t,[],void 0);let i=x(a,O()),s=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),p=[...lL(s),...pL(c)],u=await zn(p,C(t.author,a.author_default),k())??[],f=uL(m),_=fL(t.removeIndex),h=await p$({id:e,options:t,pmRoot:o,settings:a,typeToFolder:i.type_to_folder,adds:u,removes:f,removeIndexes:_}),y=u$(t,h.tests),g=await y$(t,o,h.tests),w=t.run===!0?k():void 0,b=await f$({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests}),S=Hi(b),T=t.run===!0&&t.failOnSkipped===!0&&b.some(H=>H.status==="skipped"),L=_$(t,y.runSelection,b);g&&L.push(`linked_test_trust_acknowledged:${g.acknowledged}`);let P=await g$({options:t,pmRoot:o,settings:a,itemId:h.itemId,runStartedAt:w,runResults:b,failOnSkippedTriggered:T,warnings:L}),M=P?.receipt.recorded?td([...h.testRuns,P.entry]):h.testRuns,z=Tv(t,M,P?.entry);return w$({item:h,runResults:b,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:L,recording:P,measurementProjection:z})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8371273e-fb3c-5615-bd0e-f7aeb2a0b303")}catch{}})();var v$=(e,t)=>{if(e===void 0)return;let n=te(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},b$=e=>{if(e===void 0)return;let t=ue(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},jv=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},k$=e=>e instanceof Error?e.message:String(e),S$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},E$=e=>e.trim().replaceAll(/\s+/g," "),A$=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),T$=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),C$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},I$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Vi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),qv=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),R$=e=>typeof e=="number"?e:void 0,O$=e=>{let t={assert_stdout_contains:Vi(e.assert_stdout_contains),assert_stdout_regex:Vi(e.assert_stdout_regex),assert_stderr_contains:Vi(e.assert_stderr_contains),assert_stderr_regex:Vi(e.assert_stderr_regex),assert_stdout_min_lines:R$(e.assert_stdout_min_lines),assert_json_field_equals:qv(e.assert_json_field_equals),assert_json_field_gte:qv(e.assert_json_field_gte)};return JSON.stringify(t)},x$=e=>{let t=fd(e.command);return t!==void 0?`command:${e.scope}:${E$(t)}`:`path:${e.scope}:${fd(e.path)??""}`},Kv=e=>{let t=A$(e.env_set),n=T$(e.env_clear),r=C$(e.pm_context_mode),o=I$(e.workspace_context_mode),a=e.shared_host_safe===!0?"true":"false",i=O$(e);return`${x$(e)}:${t}:${n}:${r}:${o}:${a}:${i}`},P$=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,N$=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},L$=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Wi=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
36
- `)}catch{}},$$=async(e,t,n)=>{let r=[],o=0;for(let a of e){let i=await Bi(a.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:a,tests:i.tests})}return{itemTests:r,linkedTests:o}},F$=async e=>{let t=$(e.settings.schema),n=x(e.settings,O()),r=v$(e.options.status,t),o=jv(e.options.limit,"--limit"),a=jv(e.options.offset,"--offset")??0,i=(await fe(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(s=>r?s.status===r:!0).sort((s,c)=>s.id.localeCompare(c.id));return{filteredItems:o===void 0?i.slice(a):i.slice(a,a+o),statusFilter:r,limitFilter:o,offsetFilter:a}},M$=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Kv(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,P$(t.get(o),r.timeout_seconds))}return t},D$=async(e,t)=>{let n=[],r=e.tests.map(p=>{let u=Kv(p),f=t.seenTestKeys.has(u);if(!f){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?p:{...p,timeout_seconds:_})}return{test:p,key:u,duplicate:f}}),o=n.length>0?await ud(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],a=0,i=r.map(({test:p,key:u,duplicate:f})=>{if(!f){let _=o[a];return a+=1,_}return{command:p.command,path:p.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),s=N$(i),c=Hi(i),m=await j$(e,s,i,t);return{passed:s.passed,failed:s.failed,skipped:s.skipped,trackingWarnings:m,failureCategories:c,result:{ok:s.failed===0&&!(t.options.failOnSkipped===!0&&s.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:s.passed,failed:s.failed,skipped:s.skipped,run_results:i,failure_categories:c}}},U$=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),G$=e=>e?!0:void 0,j$=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=U$(t,r.options);await Di({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:G$(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${k$(o)}`]}return[]},q$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},fd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},K$=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:lt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:M$(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:S$(),trackingAttempt:q$(),trackingResumedFrom:fd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),z$=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Hi([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},H$=async(e,t,n)=>{for(let[r,o]of e.entries()){Wi(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let a=await D$(o,t);L$(n.failureCategories,a.failureCategories),n.passed+=a.passed,n.failed+=a.failed,n.skipped+=a.skipped,n.trackingWarnings.push(...a.trackingWarnings),n.results.push(a.result),Wi(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${a.failed===0?"passed":"failed"} passed=${a.passed} failed=${a.failed} skipped=${a.skipped}`)}},B$=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=pd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},V$=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),W$=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),Y$=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await F$({pmRoot:n,settings:r,options:e}),a=b$(e.timeout),i=k(),s=await $$(o.filteredItems,t,n);return Wi(e,W$({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:a,runStartedAt:i}},J$=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},zv=async(e,t)=>{let n=await Y$(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=z$(e,n.linkedTests,n.filteredItems),a=K$({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await H$(n.itemTests,a,r),B$(e,r);let i=J$({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Wi(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),V$({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();function Hv(e,t,n){let r;if(typeof e.lines=="string")r=Pa(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.");r=Pa(`${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:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09fa5b5c-d44a-55e4-9365-a08702d8a952")}catch{}})();function Ne(e,t){let n=v(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function vn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9a4dbe8d-9341-55f1-8c4a-d476c2b338e5")}catch{}})();function X$(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:v(e.args,"name")??v(e.options,"name"),author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ge(n)}}function Q$(e){let{ctx:t,subcommand:n,name:r,author:o,force:a}=e,i=vn({list:()=>Cf(t.global),show:()=>If(r,t.global),"show-status":()=>Rf(r,t.global),"list-fields":()=>Pf(t.global),"show-field":()=>Nf(r,t.global),"remove-type":()=>Sf(r,{author:o,force:a},t.global),"remove-field":()=>xf(r,{author:o,force:a},t.global),"remove-status":()=>Tf(r,{author:o,force:a},t.global),"apply-preset":()=>Lf(v(t.args,"typePreset")??v(t.options,"typePreset"),{author:o,force:a},t.global)},n);return i?i():null}function Z$(e){let{ctx:t,name:n,author:r,force:o,aliases:a}=e,i=t.args.commands??t.options.commands,s=t.args.requiredTypes??t.options.requiredTypes;return Of(n,{type:v(t.args,"fieldType")??v(t.options,"fieldType"),commands:i===void 0?void 0:ge(i),description:v(t.args,"description")??v(t.options,"description"),cliFlag:v(t.args,"cliFlag")??v(t.options,"cliFlag"),alias:a,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:s===void 0?void 0:ge(s),author:r,force:o},t.global)}function eF(e){let{ctx:t,name:n,author:r,force:o,aliases:a}=e,i=t.args.role??t.options.role;return Af(n,{role:i===void 0?void 0:ge(i),alias:a,description:v(t.args,"description")??v(t.options,"description"),order:Fe(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function tF(e){let{ctx:t,name:n,author:r,force:o,aliases:a}=e;return kf(n,{description:v(t.args,"description")??v(t.options,"description"),defaultStatus:v(t.args,"defaultStatus")??v(t.args,"default_status")??v(t.options,"defaultStatus")??v(t.options,"default_status"),folder:v(t.args,"folder")??v(t.options,"folder"),alias:a,author:r,force:o},t.global)}function nF(e){let{ctx:t,subcommand:n,name:r,author:o,force:a}=e,i=v(t.args,"to")??Ne(t.options,"to"),s=v(t.args,"migrationId")??v(t.args,"migration_id")??v(t.options,"migrationId")??v(t.options,"migration_id"),c=v(t.args,"fieldTypeScope")??v(t.options,"fieldTypeScope")??v(t.args,"type")??v(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return vf(m,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:a},t.global)}function Bv(e){let t=X$(e);Gu(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Cn.find(o=>o===t.subcommand);if(n)return wf(n,t.name,{definition:e.args.definition??e.options.definition,policy:v(e.args,"policy")??v(e.options,"policy"),message:v(e.args,"message")??v(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=Q$(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return nF(t);if(t.subcommand==="add-field")return Z$(t);if(t.subcommand==="add-status")return eF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?$f({minCount:Fe(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):tF(t);throw Ce({command_path:"schema",token:t.subcommand,allowed:bf,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32f1d276-9fdd-5525-8c99-742d597f898a")}catch{}})();function Yi(e){return v(e.args,"target")??v(e.options,"target")}function ve(e,t=e.options){return e.id??Ne(t,"id")}async function rF(e){let t=On("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),Oc(await ht(v(e.args,"status")??v(t,"status"),t,e.global),t)}async function oF(e){let t=Ne(e.args,"query"),n=On("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Oc(await Or(t,n,e.global),n)}async function aF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await Gt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function iF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Se(await Vc(ve(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function sF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await it(ve(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function cF(e){let t=Va(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,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),Ah(ve(e),t,e.global)}function Vv(e,t){return Qf(Hv(e.options,t,Fe),e.global)}function lF(e){let t=ge(e.options.lookupPath);if(t&&t.length>0)return Vv(e,t);let n=ve(e);return e.options.discover===!0?sc(n,Ca(e.options),e.global):Xf(n,Ar(e.options),e.global)}function dF(e){return rv({subcommand:v(e.args,"subcommand")??v(e.options,"subcommand"),limit:qf(e.args,e.options)},e.global)}function mF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Tr(e.global,t)}function pF(e){let t=v(e.args,"configAction")??v(e.options,"configAction")??v(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=v(e.args,"value")??v(e.options,"value"),r=v(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Vh(v(e.args,"scope")??v(e.options,"scope")??"project",t,v(e.args,"key")??v(e.options,"key"),r,e.global,v(e.options,"policy")===void 0?n:void 0)}function uF(e){let t=e.options;return $_(L_(t),e.global)}function fF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${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 l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function _F(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=_e(e.args,e.options),a=await Ay({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:hF(e),reorderTo:fF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&Uf(e.args)&&(a.mutation_receipt=Ii(a,void 0)),t==="show"?a:Se(a,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function hF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function gF(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=t.trim().toLowerCase(),r=v(e.args,"name")??v(e.options,"name"),o=vn({list:()=>Gy(),show:()=>jy(r),lint:()=>qy(r),apply:()=>Ky(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw Ce({command_path:"profile",token:t,allowed:Uy,exit_code:64});return o()}async function yF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await ig(ve(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function wF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options);return Se(await Oy(Oa(n),e.global),{changedFields:t})}async function vF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options),r=v(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Se(await hg(Ra(o),e.global),{changedFields:t})}async function bF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=v(r,"target")??Ne(e.args,"target");return Se(await an(ve(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function kF(e){let t={...e.args,...e.options};return Zf(Ne(t,"subcommand"),v(t,"id")??e.id,v(t,"target"),Bf(t),e.global)}function SF(e){return Wf(E(process.cwd(),e.global.path),{...e.args,...e.options})}var Wv={init:e=>Nr(v(e.args,"prefix"),e.global,e.options),context:e=>gc(On("context",e.options),e.global),next:e=>Rr(On("next",e.options),e.global),eval:Sw,events:Ew,merge:Aw,workspace:Tw,meet:Li,event:Li,remind:Li,list:rF,get:e=>{let t=ve(e);return wc(t,e.global,On("get",e.options,[t]))},search:oF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ge(e.options.status);return ic(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:v(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Fe(e.options.limit,"limit")})},create:aF,copy:iF,focus:e=>il(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:sF,"item-reopen":py,restore:bF,claim:ly,release:my,"start-task":e=>_n(e,"start_task"),"pause-task":e=>_n(e,"pause_task"),"close-task":e=>_n(e,"close_task"),close:dy,comments:cF,notes:e=>xy(ve(e),Va(e.options),e.global),learnings:e=>ag(ve(e),Va(e.options),e.global),files:lF,docs:e=>Jf(ve(e),Ar(e.options),e.global),test:e=>Bi(ve(e),e.options,e.global),"test-all":e=>zv(e.options,e.global),telemetry:dF,validate:e=>Da(e.options,e.global,{runUpdate:(t,n,r)=>it(t,n,r)}),health:mF,assurance:e=>T_(e.args,e.options,e.global),contracts:e=>Sc(e.options,e.global),config:pF,activity:uF,aggregate:e=>yc(e.options,e.global),extension:e=>Gn(Yi(e),e.options,e.global),package:e=>Gn(Yi(e),e.options,e.global),install:e=>Gn(Yi(e),{...e.options,install:!0},e.global),upgrade:e=>I_(Yi(e),e.options,e.global),delete:e=>al(ve(e),e.options,e.global),deps:e=>Yf(ve(e),e.options,e.global),graph:kF,"files-discover":e=>sc(ve(e),e.options,e.global),"files-lookup":e=>Vv(e,ge(e.options.paths)),history:e=>F_(ve(e),e.options,e.global),"history-redact":e=>og(ve(e),e.options,e.global),"history-repair":Zh,"history-compact":eg,"history-attest":e=>R_(e.options,e.global),"history-author-acknowledge":SF,plan:_F,schema:Bv,profile:gF,stats:e=>Xl(e.global,Cw(e.options)),append:yF,"update-many":wF,"close-many":vF,gc:e=>C_(e.global,e.options)};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();var EF=new Map;function _d(){EF.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5417c092-2e52-5b18-bcb6-da34f07f595f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ba66cac9-25d6-559e-95d1-71db5c404807")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();function Yv(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f5ba86ac-336e-5fdb-a8fb-d8d7e7c1a504")}catch{}})();var Xv=[{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:cu().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 with evidence>" --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> "<evidence>" --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."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],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"]}],Jv=new Map;for(let e of Xv){Jv.set(e.id,e);for(let t of e.aliases)Jv.set(t,e)}function hd(){return Xv.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b11b0e04-bad1-5090-8df9-d922568db013")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8b847c-770a-556f-a7ea-151c82629318")}catch{}})();var j5=[...oo],q5=[...ao],gd=new Set(Jt.filter(e=>e.hidden).map(e=>e.alias)),Qv=su("full").filter(e=>!e.includes(" ")&&!gd.has(e)),AF=N(ho),TF=N(go),CF=N(Eo),IF=N(Ro),Zv=pr("restore",It("restore")),eb=pr("history-attest",It("history-attest")),RF=N(Oo),OF=N(Xm),xF=N(Qm),PF=N(Io),NF=N(Lo),LF=N(xo),$F=N(Po),FF=N(So),yd=[...new Set(ke.map(e=>e.canonical_argv[0]))],tb=[...new Set(ke.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],K5=new Set(fo.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),nb=ke.filter(e=>e.canonical_argv[0]==="history"),MF=nb.map(e=>e.canonical_argv[1]).join(" ");var DF=nb.map(e=>({...e,flags:N(It(e.alias))})),UF=N(yo),GF=N(wo,!1),jF=N(No),qF=N(dr),KF=N(mr),zF=N(Do),HF=N(Fo),BF=N(To),VF=N(Mo),WF=N($o),YF=N(Uo),JF=N(Ao),XF=N(Co),QF=N(bo),ZF=N(Go),eM=N(vo),wd=`${Cn.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`;var tM=N(jo),nM=`${tM} bash zsh fish`,vd=Xi(hd()),Ji="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",bd=`${Ji} upgrade`,rM=N(ko),oM=N(cr),aM=N(lr);var iM=N(It("close")),sM=N(It("close-task")),cM=N(It("release")),lM=N(It("claim"));var rb=_o.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),kd=[...Jo].join("|"),Sd=[...Jo].map(e=>`${e}=*`).join("|"),Ed=[...rb.split(" ").filter(e=>!Jo.has(e)),"-h","-V"].join("|");function Xi(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5cb75946-44c9-5e10-a39c-c981011b7efe")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b0fbba44-df4b-5cf3-968c-a0e86fd4afb5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d548143c-24be-5420-8185-f52e3941cff3")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7cfbd72-3010-53e7-946b-e65842ee4ceb")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d5f2c177-4eed-5bc5-89b5-3c5d689f902a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3e80fb-2ae7-5d3b-98bd-eacdabd2be6d")}catch{}})();var lb=Symbol("pm.active-extension-host-context");function Ge(e){return{fullChangedFields:!0,options:e}}var U=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[lb]=!0,n}run(t,n={}){return db({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return yh(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return nc(await this.list(tc(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={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...Ge(Dt(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,a={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:a})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,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={}){return this.runTyped("schema",{name:t,options:{...n,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,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,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,r={},o,a){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...a===void 0?{}:{reorderTo:a},options:Dt(r,{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,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,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",Ge(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ge(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ge(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ge(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ge(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ge(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ge(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ge(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Ge(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ge(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ge(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ge(r)})}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 yM(e={},t={}){return new U(t).context(e)}function wM(e={},t={}){return new U(t).list(e)}function vM(e={},t={}){return new U(t).listAllComplete(e)}function bM(e,t={},n={}){return new U(n).search(e,t)}function kM(e,t={},n={}){return new U(n).get(e,t)}function SM(e={},t={}){return new U(t).next(e)}function EM(e={},t={}){return new U(t).aggregate(e)}function AM(e,t={},n={}){return new U(n).comments(e,t)}function TM(e,t={},n={}){return new U(n).notes(e,t)}function CM(e,t={},n={}){return new U(n).learnings(e,t)}function IM(e,t={},n={}){return new U(n).files(e,t)}function RM(e,t={},n={}){return new U(n).filesDiscover(e,t)}function OM(e,t={},n={}){return new U(n).docs(e,t)}function xM(e,t={},n={}){return new U(n).deps(e,t)}function PM(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function NM(e,t,n={},r={}){return new U(r).append(e,t,n)}function LM(e={},t={}){return new U(t).create(e)}function $M(e,t={},n={}){return new U(n).update(e,t)}function FM(e,t,n={},r={}){return new U(r).reopen(e,t,n)}function MM(e,t,n={},r={}){return new U(r).close(e,t,n)}function DM(e,t={},n={}){return new U(n).claim(e,t)}function UM(e={},t={}){return new U(t).claimNext(e)}function GM(e,t={},n={}){return new U(n).release(e,t)}function jM(e,t={},n={}){return new U(n).copy(e,t)}function qM(e,t={},n={}){return new U(n).delete(e,t)}function KM(e,t,n={},r={}){return new U(r).restore(e,t,n)}function zM(e,t={},n={}){return new U(n).focus(e,t)}var sb=Up(),HM=new gM;function Qi(){Is(Zd()),Rs(em()),Os(tm()),xs(nm()),Ps(rm()),Ns(om()),Ls(am())}async function BM(e,t,n,r){return Gp(()=>t===void 0?sb.read(()=>cb(e,n,r)):sb.write(()=>WM(t,()=>cb(e,n,r))))}async function cb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Qi(),Ac({pmRoot:r},()=>n(null));if(!await j(re(r)))return Qi(),n(null);let o=null,a;try{let i=await A(r),s=await ir({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await sr({...s,loaded:s.loaded});a={loadResult:s,activationResult:c},Is(c.hooks),Rs(c.commands),Os(c.parsers),xs(c.preflight),Ps(c.services),Ns(c.renderers),Ls(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:s.loaded}}catch(i){Qi(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Ac({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Qi(),a&&await ws(a.loadResult,a.activationResult).catch(()=>{})}}async function VM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let a=jn(e),i=o.registrations.commands.find(m=>jn(m.action)===a)?.command??o.commands.handlers.find(m=>jn(m.command)===a)?.command;if(!i)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let s=typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension",c=await Yo({command:Ia(i),args:ge(n.args??t.args),options:ac(t,n),global:r,pm_root:o.pmRoot,sdk:uh(o.pmRoot,U.forActiveExtensionHost({pmRoot:o.pmRoot,author:s}),s,Ia(i))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function WM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function YM(e){let t=Ne(e,"action"),n=jn(t),r=vn(vh,n),o=r?.action??n,a={...e,action:o};return r?.options!==void 0&&(a.options={...r.options,...gs(e.options)}),o==="package"&&(a.options={...gs(a.options),vocabulary:"package"}),{action:o,args:a}}async function db(e){let t=YM(e),n=rc(t.args),r=zf(t.action),o=v(t.args,"cwd"),a=o??process.cwd();t.action==="init"&&(n[Rc]=a),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(a,n.path));try{return t.action==="history-attest"?await Ad(t.action,t.args,n,null):e[lb]===!0||HM.getStore()===!0?await Ad(t.action,t.args,n,null):await BM(n,o,a,i=>Ad(t.action,t.args,n,i))}finally{r&&_d()}}async function Ad(e,t,n,r){let o=oc(t,e);Ds(e,o),Hp(e,o);let a={action:e,args:t,options:o,id:v(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=vn(Wv,e),s=i?await i(a):await VM(e,t,o,n,r);if(e==="history-attest")return s;{o.resolvedOutputFormat="json";let c=Yp(e,o,s);return await mh(E(process.cwd(),n.path),c),c}}var JM={closeManyOptionsFromFlat:Ra,extensionOptionsFromArgs:ac,globalOptions:rc,mutationListOptions:Hf,normalizeActionName:jn,normalizeCommandPath:Ia,normalizeMcpUpdateOptions:Vf,normalizeMcpOptionsArrays:Kf,optionsWithAuthor:oc,readRequiredString:Ne,readScalarString:Gf,readScalarStringAllowBlank:jf,readStringArray:ge,updateManyOptionsFromFlat:Oa,withAddNoteOption:Ar,withFilesDiscoveryOptions:Ca,withMutationCompaction:_e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=JM);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3eaa41f7-77a1-5838-8a2f-2ab6a49c21ef")}catch{}})();export{xn as AGENT_PROVENANCE_DIMENSIONS,gu as BASELINE_ITEM_FORMAT_VERSION,mk as BUILTIN_AGENT_PROVENANCE_ADAPTERS,ur as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,oo as BUILTIN_ITEM_TYPE_VALUES,io as CONFIDENCE_TEXT_VALUES,yu as CURRENT_ITEM_FORMAT_VERSION,Vt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,Sn as ISSUE_SEVERITY_VALUES,Dd as ITEM_TYPE_VALUES,Tc as PM_CLI_EXPECTED_ERROR_NAME,Xb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Yb as PM_READ_OUTPUT_DIMENSIONS,Jb as PM_READ_OUTPUT_OPTION_FLAGS,Fs as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,kn as RISK_VALUES,Ak as SEMANTIC_ATTRIBUTION_LIMITS,ao as STATUS_VALUES,dk as agentSessionEnvironment,EM as aggregate,Yl as analyzeAgentProvenanceDescriptorCoverage,ik as analyzeSdkCliParameterCompleteness,NM as append,Zb as applyReadOutputDimensions,rk as applyReadOutputSessionReferences,ok as attachReadOutputSessionReceipt,sk as boundAgentEpisodeIdentity,nt as canonicalDocument,DM as claim,UM as claimNext,bu as classifyItemFormatVersion,MM as close,AM as comments,yM as context,jM as copy,LM as create,ph as createPmCliExpectedError,Wb as decodeReadOutputContinuationCursor,qM as deleteItem,xM as deps,yk as detectAgentIdentity,bk as detectHarnessIdentity,wk as diagnoseAgentIdentity,OM as docs,wu as effectiveItemFormatVersion,Yv as emptyImportedDocument,Vb as encodeReadOutputContinuationCursor,EP as evaluateSemanticAttributionCoverage,Sk as explainSourceTraceability,IM as files,RM as filesDiscover,zM as focus,kM as get,PM as graph,AP as groupHistoryByEpisode,sy as isAlreadyClaimedError,Ha as isPmCliExpectedError,ek as isReadOutputBudgetExceeded,CM as learnings,wM as list,uk as listAgentProvenanceAdapters,vM as listAllComplete,SM as next,_k as normalizeAgentProvenanceAdapterValue,vu as normalizeItemFormatVersion,Ke as normalizeItemId,te as normalizeStatusInput,TM as notes,k as nowIso,nk as parseReadOutputSession,Pa as parseSourceLineRange,ra as readAuthorEnvironment,ak as readOutputSessionRemainingTokens,_c as recordClaimSemanticAttribution,Ga as recordFocusSemanticAttribution,hc as recordReleaseSemanticAttribution,fk as registerAgentProvenanceAdapters,pk as registerHarnessSignalDescriptors,GM as release,FM as reopen,ck as resolveAgentSessionContextFromSignals,kk as resolveAuthorIdentity,Fw as resolveHistoryEpisodeGroupIdentity,Qb as resolveReadOutputDimensions,tk as resolveReadOutputEncoding,Ms as resolveReadOutputSurface,Ek as resolveSemanticLineageIds,KM as restore,db as runAction,lk as runWithAgentSessionContext,hk as runWithHarnessDetectionSignals,gk as runWithWorkspaceHarnessSignalDescriptors,bM as search,Tk as semanticAttributionAffinity,Be as serializeItemDocument,SP as summarizeAgentModelProvenance,Jl as summarizeAgentProvenance,$M as update,Ds as validateReadOutputOptions,vk as writeAuthorEnvironment};
33
+ `:"",z={stdout:`${T.text}${M}`,stderr:L.text,exitCode:b,signal:S,timedOut:w,maxBufferExceeded:!1,outputTruncated:P,spawnError:h};return yL(r,z,i,o),z}finally{await Xr(s,{recursive:!0,force:!0})}}function EL(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${qi} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function AL(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
34
+ `);return zN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>HN.test(n)&&BN.test(n))}function TL(e){return AL(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function CL(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Hi(e){let t=CL();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function yv(e,t){for(let[n,r]of Object.entries(t.env_set))ln.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)ln.has(n.toUpperCase())||delete e[n]}function IL(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function RL(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function OL(e,t,n){return{env_set:rL(e,"--env-set"),env_clear:oL(t,"--env-clear"),shared_host_safe:n===!0}}async function Jr(e,t,n=!1,r=md){if(await j(e))try{await or("seed_linked_test",async()=>{if(await r(ae.dirname(t),{recursive:!0}),n){await uv(e,t,{recursive:!0,force:!0});return}await uv(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&He(o))return;throw o}}async function wv(e,t,n,r=!1){for(let[o,a]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let i=await X(re(o));if(i!==null){let s=await A(a);await Ve({pmRoot:a,filePath:re(a),raw:i,op:"settings:write",author:C(void 0,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Jr(re(o),re(a));await Jr(ae.join(n.projectPmRoot,"extensions"),ae.join(e,"extensions"),!0),await Jr(ae.join(n.globalPmRoot,"extensions"),ae.join(t,"extensions"),!0)}async function vv(e,t){if(!await j(e))return;let n=await ld(e,{withFileTypes:!0});for(let r of n){if(qN.has(r.name))continue;let o=ae.join(e,r.name),a=ae.join(t,r.name);if(r.isDirectory()){await Jr(o,a,!0);continue}r.isFile()&&await Jr(o,a)}}async function bv(e,t){let n=await X(re(e));if(n===null||await j(Vs(e)))return;let r=await A(t);await Xr(Vs(t),{force:!0}),await Xr(re(t),{force:!0}),await Ve({pmRoot:t,filePath:re(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function er(e){if(!await j(e))return 0;let t=0,n=await ld(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||KN.has(r.name))continue;let o=ae.join(e,r.name),a;try{a=await ld(o,{withFileTypes:!0})}catch{continue}for(let i of a)i.isFile()&&Qd.some(s=>i.name.toLowerCase().endsWith(s))&&(t+=1)}return t}function xL(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function PL(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function NL(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Le(e,t):Object.is(e,t)}function LL(e,t,n){let r=[];r.push(...kv("stdout",t,e.assert_stdout_contains)),r.push(...Sv("stdout",t,e.assert_stdout_regex)),r.push(...kv("stderr",n,e.assert_stderr_contains)),r.push(...Sv("stderr",n,e.assert_stderr_regex)),r.push(...$L(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},a=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(a).length>0))return r;let i;try{i=JSON.parse(t)}catch(s){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${s instanceof Error?s.message:String(s)}`),r}for(let[s,c]of Object.entries(o)){let m=rd(i,s);if(!m.found){r.push(`assert_json_field_equals missing path "${s}"`);continue}let p=PL(c);NL(m.value,p)||r.push(`assert_json_field_equals mismatch at "${s}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(m.value)})`)}for(let[s,c]of Object.entries(a)){let m=rd(i,s);if(!m.found){r.push(`assert_json_field_gte missing path "${s}"`);continue}if(typeof m.value!="number"||!Number.isFinite(m.value)){r.push(`assert_json_field_gte path "${s}" resolved to non-numeric value`);continue}m.value<c&&r.push(`assert_json_field_gte failed at "${s}" (expected >= ${c}, actual ${m.value})`)}return r}function kv(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function Sv(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(a){r.push(`${e} regex assertion is invalid: /${o}/ (${a instanceof Error?a.message:String(a)})`)}return r}function $L(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var FL=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],ML=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function DL(e,t){let n=`${e}
35
+ ${t}`;for(let r of FL)if(r.regex.test(n))return{code:r.code};return null}function UL(e,t){let n=`${e}
36
+ ${t}`;return ML.some(r=>r.test(n))}function Ev(e){let t=zi(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Tr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&Uv(n))}function GL(e){return{root:e,schemaProjectPmPath:ae.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:ae.join(e,"schema","global"),trackerProjectPmPath:ae.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:ae.join(e,"tracker","global"),workspaceSnapshotRoot:ae.join(e,"workspace","project"),workspaceIsolatedRoot:ae.join(e,"workspace","isolated")}}function jL(e,t,n){return e.some(r=>xv(r,t,n)==="snapshot")}async function qL(e,t){let n=ae.join(e,".agents"),r=ae.join(n,"pm");await md(n,{recursive:!0}),await Xr(r,{recursive:!0,force:!0}),await DN(t,r,process.platform==="win32"?"junction":"dir")}async function KL(e,t=Pr,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function zL(e,t,n){t&&(await wv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await wv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await vv(t.projectPmRoot,e.trackerProjectPmPath),await vv(t.globalPmRoot,e.trackerGlobalPmPath),await bv(t.projectPmRoot,e.trackerProjectPmPath),await bv(t.globalPmRoot,e.trackerGlobalPmPath)))}function HL(e,t,n){return e.some(r=>{let o=r.command??"",a=o.length>0&&Lv(o),i=n?.autoPmContext===!0&&a?"auto":Pv(r,t,n?.overrideLinkedPmContext===!0);return Nv(i,a)==="tracker"})}async function BL(e,t){return{sourceProjectItemCount:t?await er(t.projectPmRoot):0,sourceGlobalItemCount:t?await er(t.globalPmRoot):0,schemaProjectItemCount:await er(e.schemaProjectPmPath),schemaGlobalItemCount:await er(e.schemaGlobalPmPath),trackerProjectItemCount:await er(e.trackerProjectPmPath),trackerGlobalItemCount:await er(e.trackerGlobalPmPath)}}function VL(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,a=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,s=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:a,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==a),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:s,trust:e.trust}}async function WL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ki(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?aL(n):!1,o=r&&n?Lv(n):!1,a=e.options?.autoPmContext===!0&&o,i=a?"auto":Pv(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),s=Nv(i,o),c=s==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await qL(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await hc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await hc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:VL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:s,autoPmContextApplied:a,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Av(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Qr(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function YL(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function JL(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return YL(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function XL(e){if(!e.linkedTest.command)return Av(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=lL(e.linkedTest.command);return t?Av(e.linkedTest,e.executionContext,t):null}function QL(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Qr(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Qr(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function ZL(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=nL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Qr(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function e$(e){return XL(e)||JL(e)||QL(e)||ZL(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!tL(e.linkedTest)?Qr(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function t$(e){let t=RL(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return yv(n,e.runtimeDirectives),yv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&IL(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Sr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Sr]="read_only"),n}function n$(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function Tv(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function r$(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:xL(e.execution),failure_category:TL(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:EL(e.execution,e.timeoutMs)}}function o$(e){if(e.options?.failOnEmptyTestRun===!0||Ev(e.linkedTest.command??"")){let n=DL(e.execution.stdout,e.execution.stderr);if(n)return Tv({...e,emptyRunSignal:n});if(Ev(e.linkedTest.command??"")&&!UL(e.execution.stdout,e.execution.stderr))return Tv({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=LL(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Qr(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):n$(e.linkedTest,e.executionContext,e.execution)}async function a$(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await SL(t,n,t$(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?o$({...e,execution:r}):r$({...e,execution:r,timeoutMs:n})}async function fd(e,t,n){let r=[],o=await Rv(ae.join(Ov(),"pm-linked-test-")),a=GL(o),i=Ki(n?.pmContext),s=eL(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=OL(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,u=T_(),f=HL(e,i,n),_=jL(e,s,n?.overrideLinkedWorkspaceContext===!0),h=await A_(u);try{await KL(a,Pr,f),await md(a.workspaceIsolatedRoot,{recursive:!0}),await zL(a,p,f),_&&await lv(u,a.workspaceSnapshotRoot);let y=await BL(a,p);for(let g=0;g<e.length;g+=1){let w=e[g],b=xv(w,s,n?.overrideLinkedWorkspaceContext===!0),S=await WL({linkedTest:w,layout:a,counts:y,sourceRoots:p,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:s,workspaceContextMode:b,currentSourceRef:h,sourceWorkspaceRoot:u}),T=e$({linkedTest:w,executionContext:S.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await a$({linkedTest:w,index:g,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Xr(a.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function i$(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,a=await q(n,t,r.id_prefix,r.item_format,o);if(!a)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await se(a,{schema:r.schema});return{itemId:a.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function s$(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function c$(e,t){let n=[...e];for(let r of t)n.some(o=>s$(o,r))||n.push(r);return n}function l$(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((a,i)=>r.has(i+1)?!1:!t.some(s=>s.kind==="command"?a.command===s.value:s.kind==="path"?a.path===s.value:a.command===s.value||a.path===s.value));return{tests:o,removed:e.length-o.length}}function d$(e,t,n,r){return l$(c$(e,t),n,r)}function m$(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function p$(e){if(m$(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function u$(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:a,adds:i,removes:s,removeIndexes:c}=e;if(i.length===0&&s.length===0&&c.length===0)return i$({id:t,pmRoot:r,settings:o,typeToFolder:a});let m=0,p=await ce({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let f=u.metadata.tests??[],_=d$(f,i,s,c);if(m=_.removed,(s.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...s.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=_.tests,{changedFields:Le(f,_.tests)?[]:["tests"]}}});return{itemId:p.item.id,tests:p.item.tests??[],testRuns:p.item.test_runs??[],changed:p.changedFields.length>0,removed:m}}function f$(e,t){p$(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:id(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?pv(t,n):void 0,o=e.timeout===void 0?void 0:ue(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:Ki(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function _$(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await fd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:lt(process.cwd())}})}function h$(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=ud(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function g$(e){let t=QN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),a=Wr(e.options.measure,o);return{run_id:XN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:a.length>0?a:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function y$(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:a,runResults:i,failOnSkippedTriggered:s,warnings:c}=e;if(t.run!==!0||!a)return;let m=g$({options:t,runStartedAt:a,runResults:i,failOnSkippedTriggered:s});if(r.testing.record_results_to_items!==!0)return{entry:m,receipt:{recorded:!1,reason:"tracking_disabled",run_id:m.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Di({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),{entry:m,receipt:{recorded:!0,reason:"recorded",run_id:m.run_id}}}catch(p){return c.push(`test_result_tracking_failed:${o}:${p instanceof Error?p.message:String(p)}`),{entry:m,receipt:{recorded:!1,reason:"write_failed",run_id:m.run_id}}}}function Cv(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),a=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),s=Number(i);if(o<=0||a.length===0||i.length===0||!Number.isFinite(s))throw new l("--metric-below must use name=value",d.USAGE);r=zw(t,a,s)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Hw(t,e.metricDiff)}}async function w$(e,t,n){if(e.acknowledgeLinkedTests===!0)return C_(t,n,k())}function v$(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:a,warnings:i,recording:s,measurementProjection:c}=e;return{ok:n.every(m=>m.status!=="failed")&&a!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:r,selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count}:void 0,fail_on_skipped_triggered:a?!0:void 0,warnings:i.length>0?i:void 0,changed:t.changed||s?.receipt.recorded===!0,...s?{evidence_recording:s.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Bi(e,t,n){let r=Nt(),o=E(process.cwd(),n.path);await I(o);let a=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Wr(t.measure,"validation"),Cv(t,[],void 0);let i=x(a,O()),s=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),p=[...dL(s),...uL(c)],u=await zn(p,C(t.author,a.author_default),k())??[],f=fL(m),_=_L(t.removeIndex),h=await u$({id:e,options:t,pmRoot:o,settings:a,typeToFolder:i.type_to_folder,adds:u,removes:f,removeIndexes:_}),y=f$(t,h.tests),g=await w$(t,o,h.tests),w=t.run===!0?k():void 0,b=await _$({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests}),S=Hi(b),T=t.run===!0&&t.failOnSkipped===!0&&b.some(H=>H.status==="skipped"),L=h$(t,y.runSelection,b);g&&L.push(`linked_test_trust_acknowledged:${g.acknowledged}`);let P=await y$({options:t,pmRoot:o,settings:a,itemId:h.itemId,runStartedAt:w,runResults:b,failOnSkippedTriggered:T,warnings:L}),M=P?.receipt.recorded?nd([...h.testRuns,P.entry]):h.testRuns,z=Cv(t,M,P?.entry);return v$({item:h,runResults:b,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:L,recording:P,measurementProjection:z})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8371273e-fb3c-5615-bd0e-f7aeb2a0b303")}catch{}})();var b$=(e,t)=>{if(e===void 0)return;let n=te(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},k$=e=>{if(e===void 0)return;let t=ue(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},qv=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},S$=e=>e instanceof Error?e.message:String(e),E$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},A$=e=>e.trim().replaceAll(/\s+/g," "),T$=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),C$=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),I$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},R$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Vi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Kv=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),O$=e=>typeof e=="number"?e:void 0,x$=e=>{let t={assert_stdout_contains:Vi(e.assert_stdout_contains),assert_stdout_regex:Vi(e.assert_stdout_regex),assert_stderr_contains:Vi(e.assert_stderr_contains),assert_stderr_regex:Vi(e.assert_stderr_regex),assert_stdout_min_lines:O$(e.assert_stdout_min_lines),assert_json_field_equals:Kv(e.assert_json_field_equals),assert_json_field_gte:Kv(e.assert_json_field_gte)};return JSON.stringify(t)},P$=e=>{let t=_d(e.command);return t!==void 0?`command:${e.scope}:${A$(t)}`:`path:${e.scope}:${_d(e.path)??""}`},zv=e=>{let t=T$(e.env_set),n=C$(e.env_clear),r=I$(e.pm_context_mode),o=R$(e.workspace_context_mode),a=e.shared_host_safe===!0?"true":"false",i=x$(e);return`${P$(e)}:${t}:${n}:${r}:${o}:${a}:${i}`},N$=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,L$=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},$$=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Wi=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
37
+ `)}catch{}},F$=async(e,t,n)=>{let r=[],o=0;for(let a of e){let i=await Bi(a.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:a,tests:i.tests})}return{itemTests:r,linkedTests:o}},M$=async e=>{let t=$(e.settings.schema),n=x(e.settings,O()),r=b$(e.options.status,t),o=qv(e.options.limit,"--limit"),a=qv(e.options.offset,"--offset")??0,i=(await fe(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(s=>r?s.status===r:!0).sort((s,c)=>s.id.localeCompare(c.id));return{filteredItems:o===void 0?i.slice(a):i.slice(a,a+o),statusFilter:r,limitFilter:o,offsetFilter:a}},D$=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=zv(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,N$(t.get(o),r.timeout_seconds))}return t},U$=async(e,t)=>{let n=[],r=e.tests.map(p=>{let u=zv(p),f=t.seenTestKeys.has(u);if(!f){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?p:{...p,timeout_seconds:_})}return{test:p,key:u,duplicate:f}}),o=n.length>0?await fd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],a=0,i=r.map(({test:p,key:u,duplicate:f})=>{if(!f){let _=o[a];return a+=1,_}return{command:p.command,path:p.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),s=L$(i),c=Hi(i),m=await q$(e,s,i,t);return{passed:s.passed,failed:s.failed,skipped:s.skipped,trackingWarnings:m,failureCategories:c,result:{ok:s.failed===0&&!(t.options.failOnSkipped===!0&&s.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:s.passed,failed:s.failed,skipped:s.skipped,run_results:i,failure_categories:c}}},G$=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),j$=e=>e?!0:void 0,q$=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=G$(t,r.options);await Di({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:j$(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${S$(o)}`]}return[]},K$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},_d=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},z$=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:lt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:D$(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:E$(),trackingAttempt:K$(),trackingResumedFrom:_d(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),H$=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Hi([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},B$=async(e,t,n)=>{for(let[r,o]of e.entries()){Wi(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let a=await U$(o,t);$$(n.failureCategories,a.failureCategories),n.passed+=a.passed,n.failed+=a.failed,n.skipped+=a.skipped,n.trackingWarnings.push(...a.trackingWarnings),n.results.push(a.result),Wi(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${a.failed===0?"passed":"failed"} passed=${a.passed} failed=${a.failed} skipped=${a.skipped}`)}},V$=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=ud(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},W$=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),Y$=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),J$=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await M$({pmRoot:n,settings:r,options:e}),a=k$(e.timeout),i=k(),s=await F$(o.filteredItems,t,n);return Wi(e,Y$({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:a,runStartedAt:i}},X$=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},Hv=async(e,t)=>{let n=await J$(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=H$(e,n.linkedTests,n.filteredItems),a=z$({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await B$(n.itemTests,a,r),V$(e,r);let i=X$({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Wi(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),W$({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();function Bv(e,t,n){let r;if(typeof e.lines=="string")r=Na(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.");r=Na(`${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:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09fa5b5c-d44a-55e4-9365-a08702d8a952")}catch{}})();function Ne(e,t){let n=v(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function vn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9a4dbe8d-9341-55f1-8c4a-d476c2b338e5")}catch{}})();function Q$(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:v(e.args,"name")??v(e.options,"name"),author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ge(n)}}function Z$(e){let{ctx:t,subcommand:n,name:r,author:o,force:a}=e,i=vn({list:()=>Rf(t.global),show:()=>Of(r,t.global),"show-status":()=>xf(r,t.global),"list-fields":()=>Lf(t.global),"show-field":()=>$f(r,t.global),"remove-type":()=>Af(r,{author:o,force:a},t.global),"remove-field":()=>Nf(r,{author:o,force:a},t.global),"remove-status":()=>If(r,{author:o,force:a},t.global),"apply-preset":()=>Ff(v(t.args,"typePreset")??v(t.options,"typePreset"),{author:o,force:a},t.global)},n);return i?i():null}function eF(e){let{ctx:t,name:n,author:r,force:o,aliases:a}=e,i=t.args.commands??t.options.commands,s=t.args.requiredTypes??t.options.requiredTypes;return Pf(n,{type:v(t.args,"fieldType")??v(t.options,"fieldType"),commands:i===void 0?void 0:ge(i),description:v(t.args,"description")??v(t.options,"description"),cliFlag:v(t.args,"cliFlag")??v(t.options,"cliFlag"),alias:a,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:s===void 0?void 0:ge(s),author:r,force:o},t.global)}function tF(e){let{ctx:t,name:n,author:r,force:o,aliases:a}=e,i=t.args.role??t.options.role;return Cf(n,{role:i===void 0?void 0:ge(i),alias:a,description:v(t.args,"description")??v(t.options,"description"),order:Me(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function nF(e){let{ctx:t,name:n,author:r,force:o,aliases:a}=e;return Ef(n,{description:v(t.args,"description")??v(t.options,"description"),defaultStatus:v(t.args,"defaultStatus")??v(t.args,"default_status")??v(t.options,"defaultStatus")??v(t.options,"default_status"),folder:v(t.args,"folder")??v(t.options,"folder"),alias:a,author:r,force:o},t.global)}function rF(e){let{ctx:t,subcommand:n,name:r,author:o,force:a}=e,i=v(t.args,"to")??Ne(t.options,"to"),s=v(t.args,"migrationId")??v(t.args,"migration_id")??v(t.options,"migrationId")??v(t.options,"migration_id"),c=v(t.args,"fieldTypeScope")??v(t.options,"fieldTypeScope")??v(t.args,"type")??v(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return kf(m,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:a},t.global)}function Vv(e){let t=Q$(e);Gu(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Cn.find(o=>o===t.subcommand);if(n)return bf(n,t.name,{definition:e.args.definition??e.options.definition,policy:v(e.args,"policy")??v(e.options,"policy"),message:v(e.args,"message")??v(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=Z$(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return rF(t);if(t.subcommand==="add-field")return eF(t);if(t.subcommand==="add-status")return tF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Mf({minCount:Me(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):nF(t);throw Ce({command_path:"schema",token:t.subcommand,allowed:Sf,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32f1d276-9fdd-5525-8c99-742d597f898a")}catch{}})();function Yi(e){return v(e.args,"target")??v(e.options,"target")}function ve(e,t=e.options){return e.id??Ne(t,"id")}async function oF(e){let t=On("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),xc(await ht(v(e.args,"status")??v(t,"status"),t,e.global),t)}async function aF(e){let t=Ne(e.args,"query"),n=On("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),xc(await Rr(t,n,e.global),n)}async function iF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await Gt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function sF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Se(await Wc(ve(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function cF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await it(ve(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function lF(e){let t=Va(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,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),Th(ve(e),t,e.global)}function Wv(e,t){return e_(Bv(e.options,t,Me),e.global)}function dF(e){let t=ge(e.options.lookupPath);if(t&&t.length>0)return Wv(e,t);let n=ve(e);return e.options.discover===!0?lc(n,Ia(e.options),e.global):Zf(n,Er(e.options),e.global)}function mF(e){return ov({subcommand:v(e.args,"subcommand")??v(e.options,"subcommand"),limit:zf(e.args,e.options)},e.global)}function pF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Ar(e.global,t)}function uF(e){let t=v(e.args,"configAction")??v(e.options,"configAction")??v(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=v(e.args,"value")??v(e.options,"value"),r=v(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Wh(v(e.args,"scope")??v(e.options,"scope")??"project",t,v(e.args,"key")??v(e.options,"key"),r,e.global,v(e.options,"policy")===void 0?n:void 0)}function fF(e){let t=e.options;return M_(F_(t),e.global)}function _F(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${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 l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function hF(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=_e(e.args,e.options),a=await Ty({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:gF(e),reorderTo:_F(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&jf(e.args)&&(a.mutation_receipt=Ii(a,void 0)),t==="show"?a:Se(a,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function gF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function yF(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=t.trim().toLowerCase(),r=v(e.args,"name")??v(e.options,"name"),o=vn({list:()=>jy(),show:()=>qy(r),lint:()=>Ky(r),apply:()=>zy(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw Ce({command_path:"profile",token:t,allowed:Gy,exit_code:64});return o()}async function wF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await sg(ve(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function vF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options);return Se(await xy(xa(n),e.global),{changedFields:t})}async function bF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options),r=v(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Se(await gg(Oa(o),e.global),{changedFields:t})}async function kF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=v(r,"target")??Ne(e.args,"target");return Se(await an(ve(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function SF(e){let t={...e.args,...e.options};return t_(Ne(t,"subcommand"),v(t,"id")??e.id,v(t,"target"),Wf(t),e.global)}function EF(e){return Jf(E(process.cwd(),e.global.path),{...e.args,...e.options})}var Yv={init:e=>Pr(v(e.args,"prefix"),e.global,e.options),context:e=>wc(On("context",e.options),e.global),next:e=>Ir(On("next",e.options),e.global),eval:Ew,events:Aw,merge:Tw,workspace:Cw,meet:Li,event:Li,remind:Li,list:oF,get:e=>{let t=ve(e);return bc(t,e.global,On("get",e.options,[t]))},search:aF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ge(e.options.status);return cc(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:v(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Me(e.options.limit,"limit")})},create:iF,copy:sF,focus:e=>sl(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:cF,"item-reopen":uy,restore:kF,claim:dy,release:py,"start-task":e=>_n(e,"start_task"),"pause-task":e=>_n(e,"pause_task"),"close-task":e=>_n(e,"close_task"),close:my,comments:lF,notes:e=>Py(ve(e),Va(e.options),e.global),learnings:e=>ig(ve(e),Va(e.options),e.global),files:dF,docs:e=>Qf(ve(e),Er(e.options),e.global),test:e=>Bi(ve(e),e.options,e.global),"test-all":e=>Hv(e.options,e.global),telemetry:mF,validate:e=>Ua(e.options,e.global,{runUpdate:(t,n,r)=>it(t,n,r)}),health:pF,assurance:e=>I_(e.args,e.options,e.global),contracts:e=>Ac(e.options,e.global),config:uF,activity:fF,aggregate:e=>vc(e.options,e.global),extension:e=>Gn(Yi(e),e.options,e.global),package:e=>Gn(Yi(e),e.options,e.global),install:e=>Gn(Yi(e),{...e.options,install:!0},e.global),upgrade:e=>O_(Yi(e),e.options,e.global),delete:e=>il(ve(e),e.options,e.global),deps:e=>Xf(ve(e),e.options,e.global),graph:SF,"files-discover":e=>lc(ve(e),e.options,e.global),"files-lookup":e=>Wv(e,ge(e.options.paths)),history:e=>D_(ve(e),e.options,e.global),"history-redact":e=>ag(ve(e),e.options,e.global),"history-repair":eg,"history-compact":tg,"history-attest":e=>x_(e.options,e.global),"history-author-acknowledge":EF,plan:hF,schema:Vv,profile:yF,stats:e=>Ql(e.global,Iw(e.options)),append:wF,"update-many":vF,"close-many":bF,gc:e=>R_(e.global,e.options)};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();var AF=new Map;function hd(){AF.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5417c092-2e52-5b18-bcb6-da34f07f595f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ba66cac9-25d6-559e-95d1-71db5c404807")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();function Jv(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f5ba86ac-336e-5fdb-a8fb-d8d7e7c1a504")}catch{}})();var Qv=[{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:lu().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 with evidence>" --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> "<evidence>" --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."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],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"]}],Xv=new Map;for(let e of Qv){Xv.set(e.id,e);for(let t of e.aliases)Xv.set(t,e)}function gd(){return Qv.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b11b0e04-bad1-5090-8df9-d922568db013")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8b847c-770a-556f-a7ea-151c82629318")}catch{}})();var G5=[...oo],j5=[...ao],yd=new Set(Jt.filter(e=>e.hidden).map(e=>e.alias)),Zv=cu("full").filter(e=>!e.includes(" ")&&!yd.has(e)),TF=N(ho),CF=N(go),IF=N(Eo),RF=N(Ro),eb=mr("restore",It("restore")),tb=mr("history-attest",It("history-attest")),OF=N(Oo),xF=N(Qm),PF=N(Zm),NF=N(Io),LF=N(Lo),$F=N(xo),FF=N(Po),MF=N(So),wd=[...new Set(ke.map(e=>e.canonical_argv[0]))],nb=[...new Set(ke.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],q5=new Set(fo.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),rb=ke.filter(e=>e.canonical_argv[0]==="history"),DF=rb.map(e=>e.canonical_argv[1]).join(" ");var UF=rb.map(e=>({...e,flags:N(It(e.alias))})),GF=N(yo),jF=N(wo,!1),qF=N(No),KF=N(lr),zF=N(dr),HF=N(Do),BF=N(Fo),VF=N(To),WF=N(Mo),YF=N($o),JF=N(Uo),XF=N(Ao),QF=N(Co),ZF=N(bo),eM=N(Go),tM=N(vo),vd=`${Cn.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`;var nM=N(jo),rM=`${nM} bash zsh fish`,bd=Xi(gd()),Ji="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",kd=`${Ji} upgrade`,oM=N(ko),aM=N(sr),iM=N(cr);var sM=N(It("close")),cM=N(It("close-task")),lM=N(It("release")),dM=N(It("claim"));var ob=_o.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),Sd=[...Jo].join("|"),Ed=[...Jo].map(e=>`${e}=*`).join("|"),Ad=[...ob.split(" ").filter(e=>!Jo.has(e)),"-h","-V"].join("|");function Xi(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5cb75946-44c9-5e10-a39c-c981011b7efe")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b0fbba44-df4b-5cf3-968c-a0e86fd4afb5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d548143c-24be-5420-8185-f52e3941cff3")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7cfbd72-3010-53e7-946b-e65842ee4ceb")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d5f2c177-4eed-5bc5-89b5-3c5d689f902a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3e80fb-2ae7-5d3b-98bd-eacdabd2be6d")}catch{}})();var db=Symbol("pm.active-extension-host-context");function je(e){return{fullChangedFields:!0,options:e}}var U=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[db]=!0,n}run(t,n={}){return mb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return wh(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return oc(await this.list(rc(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={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...je(Dt(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,a={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:a})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,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={}){return this.runTyped("schema",{name:t,options:{...n,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,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,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,r={},o,a){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...a===void 0?{}:{reorderTo:a},options:Dt(r,{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,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,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",je(t))}update(t,n={}){return this.runTyped("update",{id:t,...je(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...je(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...je(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...je(t)})}release(t,n={}){return this.runTyped("release",{id:t,...je(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...je(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...je(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...je(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...je(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...je(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...je(r)})}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 wM(e={},t={}){return new U(t).context(e)}function vM(e={},t={}){return new U(t).list(e)}function bM(e={},t={}){return new U(t).listAllComplete(e)}function kM(e,t={},n={}){return new U(n).search(e,t)}function SM(e,t={},n={}){return new U(n).get(e,t)}function EM(e={},t={}){return new U(t).next(e)}function AM(e={},t={}){return new U(t).aggregate(e)}function TM(e,t={},n={}){return new U(n).comments(e,t)}function CM(e,t={},n={}){return new U(n).notes(e,t)}function IM(e,t={},n={}){return new U(n).learnings(e,t)}function RM(e,t={},n={}){return new U(n).files(e,t)}function OM(e,t={},n={}){return new U(n).filesDiscover(e,t)}function xM(e,t={},n={}){return new U(n).docs(e,t)}function PM(e,t={},n={}){return new U(n).deps(e,t)}function NM(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function LM(e,t,n={},r={}){return new U(r).append(e,t,n)}function $M(e={},t={}){return new U(t).create(e)}function FM(e,t={},n={}){return new U(n).update(e,t)}function MM(e,t,n={},r={}){return new U(r).reopen(e,t,n)}function DM(e,t,n={},r={}){return new U(r).close(e,t,n)}function UM(e,t={},n={}){return new U(n).claim(e,t)}function GM(e={},t={}){return new U(t).claimNext(e)}function jM(e,t={},n={}){return new U(n).release(e,t)}function qM(e,t={},n={}){return new U(n).copy(e,t)}function KM(e,t={},n={}){return new U(n).delete(e,t)}function zM(e,t,n={},r={}){return new U(r).restore(e,t,n)}function HM(e,t={},n={}){return new U(n).focus(e,t)}var cb=Gp(),BM=new yM;function Qi(){Rs(em()),Os(tm()),xs(nm()),Ps(rm()),Ns(om()),Ls(am()),$s(im())}async function VM(e,t,n,r){return jp(()=>t===void 0?cb.read(()=>lb(e,n,r)):cb.write(()=>YM(t,()=>lb(e,n,r))))}async function lb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Qi(),Cc({pmRoot:r},()=>n(null));if(!await j(re(r)))return Qi(),n(null);let o=null,a;try{let i=await A(r),s=await ar({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await ir({...s,loaded:s.loaded});a={loadResult:s,activationResult:c},Rs(c.hooks),Os(c.commands),xs(c.parsers),Ps(c.preflight),Ns(c.services),Ls(c.renderers),$s(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:s.loaded}}catch(i){Qi(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Cc({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Qi(),a&&await vs(a.loadResult,a.activationResult).catch(()=>{})}}async function WM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let a=jn(e),i=o.registrations.commands.find(m=>jn(m.action)===a)?.command??o.commands.handlers.find(m=>jn(m.command)===a)?.command;if(!i)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let s=typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension",c=await Yo({command:Ra(i),args:ge(n.args??t.args),options:sc(t,n),global:r,pm_root:o.pmRoot,sdk:fh(o.pmRoot,U.forActiveExtensionHost({pmRoot:o.pmRoot,author:s}),s,Ra(i))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function YM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function JM(e){let t=Ne(e,"action"),n=jn(t),r=vn(bh,n),o=r?.action??n,a={...e,action:o};return r?.options!==void 0&&(a.options={...r.options,...ys(e.options)}),o==="package"&&(a.options={...ys(a.options),vocabulary:"package"}),{action:o,args:a}}async function mb(e){let t=JM(e),n=ac(t.args),r=Bf(t.action),o=v(t.args,"cwd"),a=o??process.cwd();t.action==="init"&&(n[Oc]=a),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(a,n.path));try{return t.action==="history-attest"?await Td(t.action,t.args,n,null):e[db]===!0||BM.getStore()===!0?await Td(t.action,t.args,n,null):await VM(n,o,a,i=>Td(t.action,t.args,n,i))}finally{r&&hd()}}async function Td(e,t,n,r){let o=ic(t,e);Us(e,o),Bp(e,o);let a={action:e,args:t,options:o,id:v(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=vn(Yv,e),s=i?await i(a):await WM(e,t,o,n,r);if(e==="history-attest")return s;{o.resolvedOutputFormat="json";let c=Jp(e,o,s);return await uh(E(process.cwd(),n.path),c),c}}var XM={closeManyOptionsFromFlat:Oa,extensionOptionsFromArgs:sc,globalOptions:ac,mutationListOptions:Vf,normalizeActionName:jn,normalizeCommandPath:Ra,normalizeMcpUpdateOptions:Yf,normalizeMcpOptionsArrays:Hf,optionsWithAuthor:ic,readRequiredString:Ne,readScalarString:qf,readScalarStringAllowBlank:Kf,readStringArray:ge,updateManyOptionsFromFlat:xa,withAddNoteOption:Er,withFilesDiscoveryOptions:Ia,withMutationCompaction:_e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=XM);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3eaa41f7-77a1-5838-8a2f-2ab6a49c21ef")}catch{}})();export{xn as AGENT_PROVENANCE_DIMENSIONS,yu as BASELINE_ITEM_FORMAT_VERSION,pk as BUILTIN_AGENT_PROVENANCE_ADAPTERS,pr as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,oo as BUILTIN_ITEM_TYPE_VALUES,io as CONFIDENCE_TEXT_VALUES,wu as CURRENT_ITEM_FORMAT_VERSION,Vt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,Sn as ISSUE_SEVERITY_VALUES,Ud as ITEM_TYPE_VALUES,mf as PM_CLI_EXPECTED_ERROR_NAME,Qb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Jb as PM_READ_OUTPUT_DIMENSIONS,Xb as PM_READ_OUTPUT_OPTION_FLAGS,Ms as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,kn as RISK_VALUES,Tk as SEMANTIC_ATTRIBUTION_LIMITS,ao as STATUS_VALUES,mk as agentSessionEnvironment,AM as aggregate,Jl as analyzeAgentProvenanceDescriptorCoverage,sk as analyzeSdkCliParameterCompleteness,LM as append,ek as applyReadOutputDimensions,ok as applyReadOutputSessionReferences,ak as attachReadOutputSessionReceipt,ck as boundAgentEpisodeIdentity,rt as canonicalDocument,UM as claim,GM as claimNext,ku as classifyItemFormatVersion,DM as close,TM as comments,wM as context,qM as copy,$M as create,pf as createPmCliExpectedError,Yb as decodeReadOutputContinuationCursor,KM as deleteItem,PM as deps,wk as detectAgentIdentity,kk as detectHarnessIdentity,vk as diagnoseAgentIdentity,xM as docs,vu as effectiveItemFormatVersion,Jv as emptyImportedDocument,Wb as encodeReadOutputContinuationCursor,AP as evaluateSemanticAttributionCoverage,Ek as explainSourceTraceability,RM as files,OM as filesDiscover,HM as focus,SM as get,NM as graph,TP as groupHistoryByEpisode,cy as isAlreadyClaimedError,Ta as isPmCliExpectedError,tk as isReadOutputBudgetExceeded,IM as learnings,vM as list,fk as listAgentProvenanceAdapters,bM as listAllComplete,EM as next,hk as normalizeAgentProvenanceAdapterValue,bu as normalizeItemFormatVersion,Ke as normalizeItemId,te as normalizeStatusInput,CM as notes,k as nowIso,rk as parseReadOutputSession,Na as parseSourceLineRange,ra as readAuthorEnvironment,ik as readOutputSessionRemainingTokens,gc as recordClaimSemanticAttribution,ja as recordFocusSemanticAttribution,yc as recordReleaseSemanticAttribution,_k as registerAgentProvenanceAdapters,uk as registerHarnessSignalDescriptors,jM as release,MM as reopen,lk as resolveAgentSessionContextFromSignals,Sk as resolveAuthorIdentity,Mw as resolveHistoryEpisodeGroupIdentity,Zb as resolveReadOutputDimensions,nk as resolveReadOutputEncoding,Ds as resolveReadOutputSurface,Ak as resolveSemanticLineageIds,zM as restore,mb as runAction,dk as runWithAgentSessionContext,gk as runWithHarnessDetectionSignals,yk as runWithWorkspaceHarnessSignalDescriptors,kM as search,Ck as semanticAttributionAffinity,Be as serializeItemDocument,EP as summarizeAgentModelProvenance,Xl as summarizeAgentProvenance,FM as update,Us as validateReadOutputOptions,bk as writeAuthorEnvironment};
37
38
  //# sourceMappingURL=sdk-core.js.map