@unbrained/pm-cli 2026.10.7 → 2026.10.8

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 (107) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +15 -0
  3. package/dist/cli-bundle/bundle-manifest.json +152 -152
  4. package/dist/cli-bundle/chunks/chunk-34L2BS2Z.js +3 -0
  5. package/dist/cli-bundle/chunks/chunk-FOLSEOJ2.js +20 -0
  6. package/dist/cli-bundle/chunks/{chunk-A4QWRU7D.js → chunk-HFCIAXLP.js} +5 -5
  7. package/dist/cli-bundle/chunks/chunk-JDTBPW4Y.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-TG3IOQUG.js → chunk-K6E2FFUT.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-VU77O6HC.js → chunk-L7U5FSZ5.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-N2PFAWVV.js → chunk-MJVRF67I.js} +3 -3
  11. package/dist/cli-bundle/chunks/{chunk-GJ2OJKRM.js → chunk-OG66KEOF.js} +79 -79
  12. package/dist/cli-bundle/chunks/{chunk-MOXX7D3F.js → chunk-RCFZ6H2Y.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-TNU56MZI.js +8 -0
  14. package/dist/cli-bundle/chunks/chunk-UGFN5NJ2.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-TON7H63A.js → chunk-ZBVAZ7XX.js} +53 -52
  16. package/dist/cli-bundle/chunks/{chunk-DWH555SN.js → chunk-ZHIMZ65M.js} +16 -16
  17. package/dist/cli-bundle/chunks/{register-list-query-CBJELTDX.js → register-list-query-PYVSPGPV.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-mutation-JRH6EGSE.js → register-mutation-WXP3YLIN.js} +2 -2
  19. package/dist/cli-bundle/chunks/register-operations-WL25C3NP.js +2 -0
  20. package/dist/cli-bundle/chunks/register-setup-PFKYNEQI.js +2 -0
  21. package/dist/cli-bundle/focused-chunks/chunk-2KSPGWLH.js +20 -0
  22. package/dist/cli-bundle/focused-chunks/{chunk-PBNQZV33.js → chunk-6TKAFFEB.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-EPOCI7ZX.js → chunk-A3W6HFFO.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-2YICTWWA.js → chunk-BDT5EALU.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-3BKRCR57.js → chunk-DRHJOG5X.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-XIGFEA3W.js → chunk-EOUORVJA.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/chunk-F2ME5MJY.js +3 -0
  28. package/dist/cli-bundle/focused-chunks/{chunk-QY4Z23QC.js → chunk-L3CZNKZE.js} +11 -11
  29. package/dist/cli-bundle/focused-chunks/{chunk-QEYEDXRI.js → chunk-LZQGEVKT.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-FWWFCLDM.js → chunk-MW2TQHZ3.js} +60 -59
  31. package/dist/cli-bundle/focused-chunks/{chunk-HMG5F5EC.js → chunk-OLCJ2PJS.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-SIR5RFJX.js → chunk-OSKXYRYZ.js} +27 -27
  33. package/dist/cli-bundle/focused-chunks/{chunk-NRSA5ZB2.js → chunk-PBPPIGUL.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-7X3QD5V4.js → chunk-PEBOVLEG.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-4FKCHJGV.js → chunk-V3EPBB6V.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-3NSZ5C4A.js → chunk-XT7JAVHI.js} +2 -2
  37. package/dist/cli-bundle/main.js +2 -2
  38. package/dist/cli-bundle/sdk-authoring.js +1 -1
  39. package/dist/cli-bundle/sdk-contracts.js +1 -1
  40. package/dist/cli-bundle/sdk-core.js +2 -2
  41. package/dist/cli-bundle/sdk-governance.js +1 -1
  42. package/dist/cli-bundle/sdk-graph.js +1 -1
  43. package/dist/cli-bundle/sdk-merge.js +51 -50
  44. package/dist/cli-bundle/sdk-query.js +1 -1
  45. package/dist/cli-bundle/sdk-runtime.js +1 -1
  46. package/dist/cli-bundle/sdk-testing.js +1 -1
  47. package/dist/cli-bundle/sdk.js +4 -4
  48. package/dist/core/extensions/item-fields.d.ts +6 -1
  49. package/dist/core/extensions/item-fields.js +1 -1
  50. package/dist/core/fs/fs-utils.d.ts +19 -4
  51. package/dist/core/fs/fs-utils.js +2 -2
  52. package/dist/core/lock/lock.d.ts +9 -2
  53. package/dist/core/lock/lock.js +2 -2
  54. package/dist/core/store/settings.js +2 -2
  55. package/dist/core/telemetry/runtime.d.ts +1 -1
  56. package/dist/core/telemetry/runtime.js +4 -4
  57. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  58. package/dist/sdk/governance/health.js +2 -2
  59. package/dist/sdk/history-repair.js +1 -1
  60. package/dist/sdk/item-transaction.js +1 -1
  61. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  62. package/dist/sdk/merge/driver.js +1 -1
  63. package/dist/sdk/merge/install.js +3 -2
  64. package/dist/sdk/merge/receipt-operation.d.ts +5 -5
  65. package/dist/sdk/merge/receipt-operation.js +1 -1
  66. package/dist/sdk/merge/receipts.d.ts +1 -1
  67. package/dist/sdk/merge/receipts.js +3 -3
  68. package/dist/sdk/merge/worktree-config.d.ts +2 -0
  69. package/dist/sdk/merge/worktree-config.js +1 -1
  70. package/dist/sdk/public-surface.json +1 -1
  71. package/docs/BUILD_AND_RELEASE_ACCEPTANCE.md +36 -100
  72. package/docs/MERGE_SAFETY.md +61 -6
  73. package/docs/PACKED_FIRST_RUN.md +26 -42
  74. package/docs/README.md +1 -0
  75. package/docs/SDK_AUDITED_MUTATIONS.md +18 -0
  76. package/docs/SDK_STORAGE_LIFECYCLE.md +35 -0
  77. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  78. package/marketplace.json +2 -2
  79. package/package.json +1 -1
  80. package/packages/pm-beads/package.json +1 -1
  81. package/packages/pm-calendar/package.json +1 -1
  82. package/packages/pm-command-kit/package.json +1 -1
  83. package/packages/pm-digital-twin/package.json +1 -1
  84. package/packages/pm-governance-audit/package.json +1 -1
  85. package/packages/pm-guide-shell/package.json +1 -1
  86. package/packages/pm-kanban/package.json +1 -1
  87. package/packages/pm-lifecycle-hooks/package.json +1 -1
  88. package/packages/pm-linked-test-adapters/package.json +1 -1
  89. package/packages/pm-search-advanced/package.json +1 -1
  90. package/packages/pm-templates/package.json +1 -1
  91. package/packages/pm-todos/package.json +1 -1
  92. package/packages/pm-vcs/package.json +1 -1
  93. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  94. package/plugins/pm-claude/package.json +2 -2
  95. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  96. package/plugins/pm-codex/package.json +2 -2
  97. package/plugins/pm-codex/plugin.json +1 -1
  98. package/runtime-dependencies.json +2 -2
  99. package/dist/cli-bundle/chunks/chunk-754AV3DC.js +0 -8
  100. package/dist/cli-bundle/chunks/chunk-CEM35QB2.js +0 -2
  101. package/dist/cli-bundle/chunks/chunk-CMIU2NDK.js +0 -20
  102. package/dist/cli-bundle/chunks/chunk-GSQK3VUT.js +0 -2
  103. package/dist/cli-bundle/chunks/chunk-WUOFG4JY.js +0 -3
  104. package/dist/cli-bundle/chunks/register-operations-FYV7CUBF.js +0 -2
  105. package/dist/cli-bundle/chunks/register-setup-M5VO6JUH.js +0 -2
  106. package/dist/cli-bundle/focused-chunks/chunk-3RJ4VK7U.js +0 -3
  107. package/dist/cli-bundle/focused-chunks/chunk-H5VREEUE.js +0 -20
@@ -1,4 +1,4 @@
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-3NSZ5C4A.js";import{a as iu,f as au,h as en,m as su,o as mr,r as ei,s as cu,t as lu,x as du}from"./focused-chunks/chunk-7X3QD5V4.js";import{$ as Gn,$a as i_,A as Sr,Ab as y_,B as yf,Bb as w_,C as Ci,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 Mi,J as bf,Ja as Ni,Jb as pc,K as kf,Ka as Ik,Kb as S_,L as Sf,La as Zf,Lb as uc,M as Ef,Ma as e_,Mb as Di,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 Ui,Z as Mf,Za as r_,_ as Df,_a as o_,aa as Uf,ab as a_,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 Li,h as df,ha as Me,hb as m_,ia as zf,ib as p_,ja as ic,jb as u_,jc as x_,ka as Hf,kb as f_,kc as j_,la as ac,lb as __,ma as Er,mb as $i,na as Ii,nb as Ut,oa as jn,ob as h_,pa as Bf,pb as Fi,qa as Ri,ra as ye,sa as sc,sb as Ar,ta as he,ua as Vf,va as Wf,wa as Oi,xa as Yf,y as gf,ya as xi,z as nc,zb as g_}from"./focused-chunks/chunk-FWWFCLDM.js";import{e as hp,g as gp,h as yp,k as vp,q as Sp}from"./focused-chunks/chunk-3BKRCR57.js";import{b as nu,c as Zo,e as ru,f as ou,g as dk}from"./focused-chunks/chunk-QEYEDXRI.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-PBNQZV33.js";import{a as ff,b as _f,c as Gi}from"./focused-chunks/chunk-HMG5F5EC.js";import{K as t_,b as hf}from"./focused-chunks/chunk-XIGFEA3W.js";import{A as F_,Aa as vc,B as M_,Fa as bc,Ha as D_,Wa as Rr,Ya as U_,Za as G_,a as mf,b as Ck,c as pf,d as Ti,g as rc,i as oc,k as cc,l as Cr,m as Rk,n as gc,o as yc,p as ji,q as Ok,r as xk,ta as wc,w as P_,x as N_,y as L_,ya as Ir,z as $_}from"./focused-chunks/chunk-EPOCI7ZX.js";import{$a as wr,A as fe,B as $n,C as _i,D as hi,G as gi,H as yi,I as Hu,Ia as Un,J as wi,Ja as nf,K as vi,Ka as ec,L as Fn,La as rf,M as Qs,N as bi,O as Bu,Oa as tc,P as Vu,Pa as of,Q as gr,Xa as Si,_a as sf,a as Gu,b as ai,c as si,cb as cf,d as ci,e as li,i as di,j as Pt,k as Nn,kb as ht,l as mi,m as Ln,mb as kr,n as pi,nb as tn,o as me,p as ui,pb as uf,q as Js,qb as Pi,r as Ye,s as Xs,sa as tf,t as ju,u as Ie,vb as qn,w as ft,x as qu,y as fi,z as Nt}from"./focused-chunks/chunk-H5VREEUE.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-NRSA5ZB2.js";import{a as pu,b as uu,c as fu}from"./focused-chunks/chunk-4FKCHJGV.js";import{$ as Um,A as yo,Aa as ip,B as wm,Ba as ap,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-2YICTWWA.js";import{$ as Eu,$a as zu,A as Ak,Aa as _r,Ab as I,B as Tk,Bb as K,C as Pn,Cb as ae,D as C,Db as Xu,Fb as _e,Gb as Qu,H as ut,Ha as Lu,Hb as ki,Ib as _t,Ja as Vs,Jb as Zu,Kb as se,L as gu,Lb as ef,M as oi,Ma as $u,N as yu,Na as ii,O as wu,Oa as We,P as vu,Pb as af,Q as bu,Qa as Fu,R as ku,Ra as Mu,T as ee,Ta as Du,U as js,Ua as Ws,V as re,Va as Ys,Vb as vr,Wa as Uu,Wb as br,X as qs,Xa as A,Xb as Ei,Y as Su,Ya as Fe,Yb as Mt,Z as Ve,Za as Ce,_ as rt,_a as Ku,a as ti,aa as Au,ab as Lt,b as mk,bc as Ai,c as pk,ca as Tu,cb as ze,d as uk,da as Cu,db as hr,e as fk,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 ni,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 _k,q as hk,r as gk,ra as $e,s as yk,sa as xt,sc as Xf,t as wk,u as vk,ua as Hs,v as bk,va as ur,vb as $t,w as kk,wa as fr,x as Sk,xa as Bs,xb as Ft,y as ri,ya as ot,z as Ek,za as Nu,zb as Ju}from"./focused-chunks/chunk-SIR5RFJX.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-3RJ4VK7U.js";import{e as mu}from"./focused-chunks/chunk-YLVHHWHN.js";import{$ as d,$a as Zd,$d as Xo,Ab as ir,B as Gd,Bb as vs,C as jd,Cb as ar,Cc as jp,D as qd,De as Xp,E as Kd,Ec as Rs,Ed as Xb,F as zd,Fc as Os,Fd as Qb,G as Hd,Gc as xs,H as ds,Ha as An,Hb as Se,Hc as Ps,Hd as Zb,He as ak,I as ms,Ic as Ns,Ie as sk,J as ps,Ja as Xd,Jb as B,Jc as Ls,Jd as ek,Je as ck,K as us,Kc as $s,Kd as tk,Ke as lk,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 nk,Tc as Yo,Td as rk,U as hs,Ua as x,Ud as ok,Va as ke,Vc as Ee,Vd as ik,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 ne,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 im,oc as Up,p as Ud,pa as Jd,pb as am,pc as Is,q as io,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 Be,v as Vt,va as J,vd as Fs,ve as On,w as ct,wc as Gp,x as kn,xa as te,y as Sn,z as ao,za as En,ze as Jp}from"./focused-chunks/chunk-QY4Z23QC.js";import{AsyncLocalStorage as wM}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 Pk=Gs("list").properties.outputSession,Nk={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:{...Pk},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},ce={type:"string",description:"pm item id, for example pm-abc1."},Lk=`Operation name (one of): ${Is.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,$k={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."}},Fk={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 Mk=[{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:Lk},id:ce,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."},...Nk},["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"},...Fk},["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"},...$k})},{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:ce,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:ce,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:ce,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:ce,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:ce,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:ce,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:ce,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:ce,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:ce,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:ce,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:ce,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:ce,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:ce,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:ce,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:ce,target:ce,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:ce,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."}})}],Dk={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"},Uk=Mk.map(e=>{let t=Dk[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 Uk.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"]]]),Gk=["--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"]),Ki=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]))),ih=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Ec=new Map(ih.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),jk=10,qk=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."]]),ah=[["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]],Kk=[...ah.map(([e,t])=>e==="init"?[e,Im]:[e,t]),["upgrade",cr]],zk=[...ah.map(([e,t])=>[`extension ${e}`,t]),...Kk.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",ip],["health",Co],["assurance",ap],...pp,["contracts",Go],["completion",jo],["activity",dp],...[...th].map(e=>[e,ho])],Or=new Map(zk);for(let{alias:e,canonical:t}of Se){let n=Or.get(e);n!==void 0&&Or.set(t,n)}function Hk(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=Se.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Ts.includes(e)?we(e):e.startsWith("extension-")?we(`extension ${e.slice(10)}`):e.startsWith("package-")?we(`package ${e.slice(8)}`):e.startsWith("item-")?we(`item ${e.slice(5)}`):e.startsWith("test-runs-")?we(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?we(`templates ${e.slice(10)}`):Ki.has(e)?rh.get(e)??we(e):null}function Bk(e,t){let n=B(t);return n!==t||Se.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=>we(t)).filter(t=>t.length>0)}function Vk(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of gt(o.command_path)){let a=i.split(" ").filter(s=>s.length>0);if(a.length!==0)for(let s=a.length;s>0;s-=1){let c=a.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function qi(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 Wk(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 i=o.action;return typeof i!="object"||i===null?!1:i.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 i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function we(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function sh(e){return e.replace(/\s+/g,"-")}function it(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=it(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 Yk(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 i=it(e.description);i&&(o.description=i);let a=it(e.value_name);a&&(o.value_name=a);let s=[it(e.value_type),it(e.type),a?"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=we(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;i.sourceDedupe.has(a)||(i.sourceDedupe.add(a),i.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=Yk(s);if(!c)continue;let m=`${c.flag}|${c.short??""}`;i.dedupe.has(m)||(i.dedupe.add(m),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,a)=>{let s=i.layer.localeCompare(a.layer);return s!==0?s:(i.name??"").localeCompare(a.name??"")})});return n}function Jk(e){let t=ch(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=we(i.command);if(a.length===0)continue;let s=it(i.action)??sh(a),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let p=it(m.name);return p?{name:p,required:m.required===!0,variadic:m.variadic===!0,description:it(m.description)}:null}).filter(m=>m!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},command:a,action:s,source:{layer:i.layer,name:i.name},description:it(i.description),intent:it(i.intent),arguments:c,flags:t.get(a)?.flags??[],examples:W_(i.examples),failure_hints:W_(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(we(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((a,s)=>a.localeCompare(s))){let a=n.get(i);o.push(Xk(i,a,t.get(i)?.flags??[]))}return o}function Xk(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 Qk(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 Zk(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 eS(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 tS(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]=Zk(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=Qk(o);!i||n[i]!==void 0||(n[i]=eS(o,e.action),o.required===!0&&r.push(i))}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 nS(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 rS(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((i,a)=>i.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let a=`${i.flag}|${i.short??""}`;if(!o.has(a))o.add(a),r.flags.push(i);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);s&&nS(s,i)}}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 oS(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(ne(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await ir({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await ar({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>we(s.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function iS(e,t={}){let n=new Map;for(let r of Cs){let o=Ki.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=V_(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Ki)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:Se.find(o=>o.alias===r.command)?.canonical??we(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function aS(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(a=>t.handlers.has(a)||t.handlers.has(B(a))),o=n.map(a=>nh.get(B(a))).find(a=>typeof a=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?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 sS(e){return rn.has(B(e))?!1:Or.has(e)}function cS(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 lS(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function dS(e){let t=new Map;for(let r of e.definitions){let o=J_(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>lS(s)).find(s=>s!==null),a=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=i?{flag:o,short:i}:{flag:o},p=`${m.flag}|${m.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(m));for(let u of a){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 i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return Ss(n)}function mS(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Se){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=sS(a),c=s?lh(a):[],m=n.get(cS(a))??[],p=i.get(a),u=X_(c,m),f=X_(u,p?.flags??[]),_=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:a,flags:f,...r?{canonical_command:mh(a),visibility:dh(a,o),positionals:pm(a)?.slots??[],flag_invocations:mr(a,f)}:{},provider:_,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function pS(e,t=Jt){let n=new Set(e),r=new Map;for(let o of ih){let i=o.aliases.filter(a=>n.has(a));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function uS(){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)),i=[...new Set(o.map(s=>Ae("create",s)))].sort((s,c)=>s.localeCompare(c)),a=[...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:i,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function fS(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){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 _S(e,t){let n=xr(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let a=i.properties;if(typeof a!="object"||a===null)return i;let s=a.action;return typeof s!="object"||s===null||s.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function hS(e){let t=qi(e.action)!==void 0||qi(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,i=e.flagsOnly===!0,a=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,m=qi(e.action),p=qi(e.command),u=!r&&!c&&!o&&!i&&!a&&!m&&!p;return{selectedAction:m,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:a,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function gS(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 yS(e,t=A){try{return await t(e)}catch{return structuredClone(At)}}async function wS(e,t,n){let r=await yS(t),o=await oS(e),i=x(r,o.registrations??O()),a=nt(r.schema),s=Jk(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:$(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:dS(a),createRequiredOptionContracts:fS(i),extensionContracts:s,mergedExtensionContracts:rS(s.filter(c=>zi(n,c.command,s))),extensionFlagMap:ch(o.flagRegistrations)}}function Z_(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ki.has(e.selectedAction)||e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand)))}function vS(e,t){let n=iS(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(i=>i.action===o.action)?.tier??ei(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:Hk(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function bS(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 kS(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=Se.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>we(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function SS(e,t){let n=t.slice(0,jk),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,qk),a=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:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function ES(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 AS(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 TS(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 SS(e.selectedCommand,n);let r=nh.get(B(e.selectedCommand));throw r?ES(e.selectedCommand,r):AS(e.selectedCommand)}function CS(e,t){let n=vS(e,t.mergedExtensionContracts);bS(e,n);let r=kS(n,t.mergedExtensionContracts);TS(e,r);let o=e.selectedCommand?oh.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:Bk(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.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 a=e.selectedAction?i.filter(m=>m.action===e.selectedAction):i,s=[...new Map(a.map(m=>aS(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:i,scopedActionDescriptors:a,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function IS(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 RS(e){let t=Zp,n=xr(t),r=IS(t),o=e.filter(i=>!r.has(i.action)).map(i=>tS(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function eh(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?Wk(n,e.selectedAction):e.selectedCommand?kc(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):kc(n,r);return e.runtimeOnly&&!e.selectedAction?kc(o,new Set(t.actions)):o}function OS(e,t,n){let r=RS(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?_S(eh(e,n,r),t.createRequiredOptionContracts):eh(e,n,r);return{mergedSchema:r,filteredSchema:o}}function xS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Vk(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function dh(e,t){return t.find(n=>B(n.command)===B(e))?.tier??ei(e)}function zi(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||dh(t,n)!=="internal"}function PS(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)&&zi(e,o,n))}function mh(e){let t=Se.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 NS=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"]]),LS=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function $S(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(" "),i=o.at(-1),a=o.slice(0,-1).join(" "),s=NS.get(i),c=LS.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function FS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(we))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=Fs(i,{generateFallback:!0}),s=i.split(" ")[0],c=Ec.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),m=new Set([...lh(i).map(f=>f.flag),...t.filter(f=>gt(f.command).some(_=>B(_)===B(i))).flatMap(f=>f.flags.map(_=>_.flag))]),p=(H_.get(B(i))??H_.get(c)??Gk).filter(f=>m.has(f)),u=$S(i,t);return{command:i,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function MS(e){return e.map(t=>({budget:Fs(t,{generateFallback:!0}),envelope:du(t)}))}function DS(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,i=o.join(","),a=t.get(i)??{commands:[],exit_codes:o};a.commands.push(n),t.set(i,a)}return[...t.values()]}function US(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(i=>r.has(i)))}return t.extensionContracts.filter(r=>zi(e,r.command,t.extensionContracts))}function GS(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 jS(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,i])=>[o,[...new Set(i.map(a=>`--${a.cli_flag}`))].sort((a,s)=>a.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,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function qS(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 KS(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=mS(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(fu).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...uu],compact_fields:[...pu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:a})=>({canonical:i,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function zS(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=uS();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function HS(e,t,n,r){e.command_summaries=FS(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(we))].filter(o=>Ds(o)!==void 0).sort((o,i)=>o.localeCompare(i)).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,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:ks}:{}}}async function Ac(e,t){let n=hS(e);gS(n);let r=E(process.cwd(),t.path),o=await wS(t,r,n),i=CS(n,o),a=OS(n,o,i),s=xS(n,i),c=PS(n,s,o.extensionContracts),m=GS(n,a,i,c),p=US(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&HS(m,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return m;let f=pS(i.commandCatalog.filter(_=>zi(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||jS(m,o,n),qS(m,n,a,p),KS(m,n,o,c,f),zS(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=MS(c),m.diagnostic_output_contracts=zp,m.command_exit_contracts={vocabulary:iu,command_sets:DS(c)}),m}import{readFile as BS}from"node:fs/promises";import VS 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 Hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function WS(e,t,n){if(!Hi(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:Hi(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)=>WS(r,t,o))}async function YS(e){let t=VS.join(e,Tc),n;try{n=await BS(t,"utf8")}catch(o){if(Wt(o))return[];throw await Ju(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Tc}: ${i}`,{cause:o})}return ph(r,Tc)}function JS(e){if(!Hi(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Hi(n)?n.contextIntents??n.context_intents:void 0}function XS(e){return e.flatMap(t=>{let n=JS(t.module);return n===void 0?[]:ph(n,`package ${t.name}`)})}async function QS(e){let t=await YS(e.pmRoot),n=XS(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Cc(e,t){let n=await QS(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(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as ZS}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 eE(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(Ys(t));for(let i of n){let a=i.split("."),s=o;for(let p of a){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: ${i}. Select a declared inline object path.`,d.USAGE);s=u[p]}if(gs(s)===null)throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,d.USAGE);let c=r,m=o;for(let p of a.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,a.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return Le(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
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-XT7JAVHI.js";import{a as iu,f as au,h as en,m as su,o as mr,r as ei,s as cu,t as lu,x as du}from"./focused-chunks/chunk-PEBOVLEG.js";import{$ as Gn,$a as i_,A as Sr,Ab as y_,B as yf,Bb as w_,C as Ci,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 Mi,J as bf,Ja as Ni,Jb as pc,K as kf,Ka as Ik,Kb as S_,L as Sf,La as Zf,Lb as uc,M as Ef,Ma as e_,Mb as Di,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 Ui,Z as Mf,Za as r_,_ as Df,_a as o_,aa as Uf,ab as a_,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 Li,h as df,ha as Me,hb as m_,ia as zf,ib as p_,ja as ic,jb as u_,jc as x_,ka as Hf,kb as f_,kc as j_,la as ac,lb as __,ma as Er,mb as $i,na as Ii,nb as Ut,oa as jn,ob as h_,pa as Bf,pb as Fi,qa as Ri,ra as ye,sa as sc,sb as Ar,ta as he,ua as Vf,va as Wf,wa as Oi,xa as Yf,y as gf,ya as xi,z as nc,zb as g_}from"./focused-chunks/chunk-MW2TQHZ3.js";import{e as hp,g as gp,h as yp,k as vp,q as Sp}from"./focused-chunks/chunk-DRHJOG5X.js";import{b as nu,c as Zo,e as ru,f as ou,g as dk}from"./focused-chunks/chunk-LZQGEVKT.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-6TKAFFEB.js";import{a as ff,b as _f,c as Gi}from"./focused-chunks/chunk-OLCJ2PJS.js";import{K as t_,b as hf}from"./focused-chunks/chunk-EOUORVJA.js";import{A as F_,Aa as vc,B as M_,Fa as bc,Ha as D_,Wa as Rr,Ya as U_,Za as G_,a as mf,b as Ck,c as pf,d as Ti,g as rc,i as oc,k as cc,l as Cr,m as Rk,n as gc,o as yc,p as ji,q as Ok,r as xk,ta as wc,w as P_,x as N_,y as L_,ya as Ir,z as $_}from"./focused-chunks/chunk-A3W6HFFO.js";import{$a as wr,A as fe,B as $n,C as _i,D as hi,G as gi,H as yi,I as Hu,Ia as Un,J as wi,Ja as nf,K as vi,Ka as ec,L as Fn,La as rf,M as Qs,N as bi,O as Bu,Oa as tc,P as Vu,Pa as of,Q as gr,Xa as Si,_a as sf,a as Gu,b as ai,c as si,cb as cf,d as ci,e as li,i as di,j as Pt,k as Nn,kb as ht,l as mi,m as Ln,mb as kr,n as pi,nb as tn,o as me,p as ui,pb as uf,q as Js,qb as Pi,r as Ye,s as Xs,sa as tf,t as ju,u as Ie,vb as qn,w as ft,x as qu,y as fi,z as Nt}from"./focused-chunks/chunk-2KSPGWLH.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-PBPPIGUL.js";import{a as pu,b as uu,c as fu}from"./focused-chunks/chunk-V3EPBB6V.js";import{$ as Um,A as yo,Aa as ip,B as wm,Ba as ap,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-BDT5EALU.js";import{$ as Eu,$a as zu,A as Ak,Aa as _r,Ab as I,B as Tk,Bb as K,C as Pn,Cb as ae,D as C,Db as Xu,Fb as _e,Gb as Qu,H as ut,Ha as Lu,Hb as ki,Ib as _t,Ja as Vs,Jb as Zu,Kb as se,L as gu,Lb as ef,M as oi,Ma as $u,N as yu,Na as ii,O as wu,Oa as We,P as vu,Pb as af,Q as bu,Qa as Fu,R as ku,Ra as Mu,T as ee,Ta as Du,U as js,Ua as Ws,V as re,Va as Ys,Vb as vr,Wa as Uu,Wb as br,X as qs,Xa as A,Xb as Ei,Y as Su,Ya as Fe,Yb as Mt,Z as Ve,Za as Ce,_ as rt,_a as Ku,a as ti,aa as Au,ab as Lt,b as mk,bc as Ai,c as pk,ca as Tu,cb as ze,d as uk,da as Cu,db as hr,e as fk,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 ni,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 _k,q as hk,r as gk,ra as $e,s as yk,sa as xt,sc as Xf,t as wk,u as vk,ua as Hs,v as bk,va as ur,vb as $t,w as kk,wa as fr,x as Sk,xa as Bs,xb as Ft,y as ri,ya as ot,z as Ek,za as Nu,zb as Ju}from"./focused-chunks/chunk-OSKXYRYZ.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-F2ME5MJY.js";import{e as mu}from"./focused-chunks/chunk-YLVHHWHN.js";import{$ as d,$a as E,$c as Zt,Aa as En,Ae as Jp,B as Gd,Bb as ir,C as jd,Cb as vs,D as qd,Db as ar,Dc as jp,E as Kd,Ee as Xp,F as zd,Fc as Rs,Fd as Xb,G as Hd,Gc as Os,Gd as Qb,H as ds,Hc as xs,I as ms,Ia as An,Ib as Se,Ic as Ps,Id as Zb,Ie as ak,J as ps,Jc as Ns,Je as sk,K as us,Ka as Xd,Kb as B,Kc as Ls,Kd as ek,Ke as ck,L as fs,Lc as $s,Ld as tk,Le as lk,M as _s,Ma as gs,Mb as Jt,Mc as O,Md as Ms,Me as Qo,Na as ys,Nc as In,Nd as Ds,Ne as Qp,Oc as Qt,Od as Us,P as so,Pc as Y,Pd as Hp,Qa as ws,Qc as Wo,Ra as nr,Rc as Rn,Rd as Bp,Sa as Ae,Sb as Cn,Sd as nk,U as hs,Uc as Yo,Ud as rk,Va as x,Vd as ok,W as Bd,Wa as ke,Wc as Ee,Wd as ik,Xa as po,Xc as Jo,Ya as Tn,Yd as k,Z as At,Za as rr,_a as Qd,_c as qp,aa as l,ab as Zd,ae as Xo,bb as lt,bc as Op,cb as ne,cc as xp,ce as ie,db as dt,dc as Pp,ec as Np,fb as tt,fc as Lp,fe as Te,gb as uo,gc as $p,hc as Ts,ia as Vd,ic as Fp,ka as Wd,kb as em,kc as Mp,lb as tm,lc as Dp,le as Vp,ma as mo,mb as nm,nb as rm,nd as Kp,o as oo,oa as Yd,ob as om,oc as Cs,p as Ud,pa as Jd,pb as im,pc as Up,q as io,qb as am,qc as Is,r as ls,rd as zp,sa as j,sb as or,se as Wp,ta as Wt,tb as Yt,te as Yp,ua as Be,ub as Le,v as Vt,va as J,w as ct,wd as Fs,we as On,x as kn,xc as Gp,y as Sn,ya as te,z as ao}from"./focused-chunks/chunk-L3CZNKZE.js";import{AsyncLocalStorage as wM}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 Pk=Gs("list").properties.outputSession,Nk={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:{...Pk},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},ce={type:"string",description:"pm item id, for example pm-abc1."},Lk=`Operation name (one of): ${Is.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,$k={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."}},Fk={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 Mk=[{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:Lk},id:ce,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."},...Nk},["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"},...Fk},["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"},...$k})},{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:ce,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:ce,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:ce,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:ce,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:ce,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:ce,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:ce,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:ce,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:ce,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:ce,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:ce,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:ce,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:ce,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:ce,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:ce,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:ce,target:ce,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:ce,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."}})}],Dk={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"},Uk=Mk.map(e=>{let t=Dk[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 Uk.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"]]]),Gk=["--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"]),Ki=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]))),ih=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Ec=new Map(ih.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),jk=10,qk=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."]]),ah=[["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]],Kk=[...ah.map(([e,t])=>e==="init"?[e,Im]:[e,t]),["upgrade",cr]],zk=[...ah.map(([e,t])=>[`extension ${e}`,t]),...Kk.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",ip],["health",Co],["assurance",ap],...pp,["contracts",Go],["completion",jo],["activity",dp],...[...th].map(e=>[e,ho])],Or=new Map(zk);for(let{alias:e,canonical:t}of Se){let n=Or.get(e);n!==void 0&&Or.set(t,n)}function Hk(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=Se.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Ts.includes(e)?we(e):e.startsWith("extension-")?we(`extension ${e.slice(10)}`):e.startsWith("package-")?we(`package ${e.slice(8)}`):e.startsWith("item-")?we(`item ${e.slice(5)}`):e.startsWith("test-runs-")?we(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?we(`templates ${e.slice(10)}`):Ki.has(e)?rh.get(e)??we(e):null}function Bk(e,t){let n=B(t);return n!==t||Se.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=>we(t)).filter(t=>t.length>0)}function Vk(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of gt(o.command_path)){let a=i.split(" ").filter(s=>s.length>0);if(a.length!==0)for(let s=a.length;s>0;s-=1){let c=a.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function qi(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 Wk(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 i=o.action;return typeof i!="object"||i===null?!1:i.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 i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function we(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function sh(e){return e.replace(/\s+/g,"-")}function it(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=it(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 Yk(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 i=it(e.description);i&&(o.description=i);let a=it(e.value_name);a&&(o.value_name=a);let s=[it(e.value_type),it(e.type),a?"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=we(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;i.sourceDedupe.has(a)||(i.sourceDedupe.add(a),i.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=Yk(s);if(!c)continue;let m=`${c.flag}|${c.short??""}`;i.dedupe.has(m)||(i.dedupe.add(m),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,a)=>{let s=i.layer.localeCompare(a.layer);return s!==0?s:(i.name??"").localeCompare(a.name??"")})});return n}function Jk(e){let t=ch(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=we(i.command);if(a.length===0)continue;let s=it(i.action)??sh(a),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let p=it(m.name);return p?{name:p,required:m.required===!0,variadic:m.variadic===!0,description:it(m.description)}:null}).filter(m=>m!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},command:a,action:s,source:{layer:i.layer,name:i.name},description:it(i.description),intent:it(i.intent),arguments:c,flags:t.get(a)?.flags??[],examples:W_(i.examples),failure_hints:W_(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(we(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((a,s)=>a.localeCompare(s))){let a=n.get(i);o.push(Xk(i,a,t.get(i)?.flags??[]))}return o}function Xk(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 Qk(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 Zk(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 eS(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 tS(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]=Zk(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=Qk(o);!i||n[i]!==void 0||(n[i]=eS(o,e.action),o.required===!0&&r.push(i))}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 nS(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 rS(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((i,a)=>i.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let a=`${i.flag}|${i.short??""}`;if(!o.has(a))o.add(a),r.flags.push(i);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);s&&nS(s,i)}}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 oS(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(ne(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await ir({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await ar({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>we(s.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function iS(e,t={}){let n=new Map;for(let r of Cs){let o=Ki.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=V_(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Ki)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:Se.find(o=>o.alias===r.command)?.canonical??we(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function aS(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(a=>t.handlers.has(a)||t.handlers.has(B(a))),o=n.map(a=>nh.get(B(a))).find(a=>typeof a=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?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 sS(e){return rn.has(B(e))?!1:Or.has(e)}function cS(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 lS(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function dS(e){let t=new Map;for(let r of e.definitions){let o=J_(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>lS(s)).find(s=>s!==null),a=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=i?{flag:o,short:i}:{flag:o},p=`${m.flag}|${m.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(m));for(let u of a){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 i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return Ss(n)}function mS(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Se){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=sS(a),c=s?lh(a):[],m=n.get(cS(a))??[],p=i.get(a),u=X_(c,m),f=X_(u,p?.flags??[]),_=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:a,flags:f,...r?{canonical_command:mh(a),visibility:dh(a,o),positionals:pm(a)?.slots??[],flag_invocations:mr(a,f)}:{},provider:_,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function pS(e,t=Jt){let n=new Set(e),r=new Map;for(let o of ih){let i=o.aliases.filter(a=>n.has(a));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function uS(){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)),i=[...new Set(o.map(s=>Ae("create",s)))].sort((s,c)=>s.localeCompare(c)),a=[...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:i,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function fS(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){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 _S(e,t){let n=xr(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let a=i.properties;if(typeof a!="object"||a===null)return i;let s=a.action;return typeof s!="object"||s===null||s.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function hS(e){let t=qi(e.action)!==void 0||qi(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,i=e.flagsOnly===!0,a=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,m=qi(e.action),p=qi(e.command),u=!r&&!c&&!o&&!i&&!a&&!m&&!p;return{selectedAction:m,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:a,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function gS(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 yS(e,t=A){try{return await t(e)}catch{return structuredClone(At)}}async function wS(e,t,n){let r=await yS(t),o=await oS(e),i=x(r,o.registrations??O()),a=nt(r.schema),s=Jk(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:$(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:dS(a),createRequiredOptionContracts:fS(i),extensionContracts:s,mergedExtensionContracts:rS(s.filter(c=>zi(n,c.command,s))),extensionFlagMap:ch(o.flagRegistrations)}}function Z_(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ki.has(e.selectedAction)||e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand)))}function vS(e,t){let n=iS(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(i=>i.action===o.action)?.tier??ei(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:Hk(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function bS(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 kS(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=Se.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>we(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function SS(e,t){let n=t.slice(0,jk),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,qk),a=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:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function ES(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 AS(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 TS(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 SS(e.selectedCommand,n);let r=nh.get(B(e.selectedCommand));throw r?ES(e.selectedCommand,r):AS(e.selectedCommand)}function CS(e,t){let n=vS(e,t.mergedExtensionContracts);bS(e,n);let r=kS(n,t.mergedExtensionContracts);TS(e,r);let o=e.selectedCommand?oh.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:Bk(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.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 a=e.selectedAction?i.filter(m=>m.action===e.selectedAction):i,s=[...new Map(a.map(m=>aS(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:i,scopedActionDescriptors:a,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function IS(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 RS(e){let t=Zp,n=xr(t),r=IS(t),o=e.filter(i=>!r.has(i.action)).map(i=>tS(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function eh(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?Wk(n,e.selectedAction):e.selectedCommand?kc(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):kc(n,r);return e.runtimeOnly&&!e.selectedAction?kc(o,new Set(t.actions)):o}function OS(e,t,n){let r=RS(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?_S(eh(e,n,r),t.createRequiredOptionContracts):eh(e,n,r);return{mergedSchema:r,filteredSchema:o}}function xS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Vk(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function dh(e,t){return t.find(n=>B(n.command)===B(e))?.tier??ei(e)}function zi(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||dh(t,n)!=="internal"}function PS(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)&&zi(e,o,n))}function mh(e){let t=Se.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 NS=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"]]),LS=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function $S(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(" "),i=o.at(-1),a=o.slice(0,-1).join(" "),s=NS.get(i),c=LS.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function FS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(we))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=Fs(i,{generateFallback:!0}),s=i.split(" ")[0],c=Ec.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),m=new Set([...lh(i).map(f=>f.flag),...t.filter(f=>gt(f.command).some(_=>B(_)===B(i))).flatMap(f=>f.flags.map(_=>_.flag))]),p=(H_.get(B(i))??H_.get(c)??Gk).filter(f=>m.has(f)),u=$S(i,t);return{command:i,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function MS(e){return e.map(t=>({budget:Fs(t,{generateFallback:!0}),envelope:du(t)}))}function DS(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,i=o.join(","),a=t.get(i)??{commands:[],exit_codes:o};a.commands.push(n),t.set(i,a)}return[...t.values()]}function US(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(i=>r.has(i)))}return t.extensionContracts.filter(r=>zi(e,r.command,t.extensionContracts))}function GS(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 jS(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,i])=>[o,[...new Set(i.map(a=>`--${a.cli_flag}`))].sort((a,s)=>a.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,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function qS(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 KS(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=mS(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(fu).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...uu],compact_fields:[...pu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:a})=>({canonical:i,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function zS(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=uS();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function HS(e,t,n,r){e.command_summaries=FS(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(we))].filter(o=>Ds(o)!==void 0).sort((o,i)=>o.localeCompare(i)).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,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:ks}:{}}}async function Ac(e,t){let n=hS(e);gS(n);let r=E(process.cwd(),t.path),o=await wS(t,r,n),i=CS(n,o),a=OS(n,o,i),s=xS(n,i),c=PS(n,s,o.extensionContracts),m=GS(n,a,i,c),p=US(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&HS(m,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return m;let f=pS(i.commandCatalog.filter(_=>zi(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||jS(m,o,n),qS(m,n,a,p),KS(m,n,o,c,f),zS(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=MS(c),m.diagnostic_output_contracts=zp,m.command_exit_contracts={vocabulary:iu,command_sets:DS(c)}),m}import{readFile as BS}from"node:fs/promises";import VS 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 Hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function WS(e,t,n){if(!Hi(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:Hi(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)=>WS(r,t,o))}async function YS(e){let t=VS.join(e,Tc),n;try{n=await BS(t,"utf8")}catch(o){if(Wt(o))return[];throw await Ju(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Tc}: ${i}`,{cause:o})}return ph(r,Tc)}function JS(e){if(!Hi(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Hi(n)?n.contextIntents??n.context_intents:void 0}function XS(e){return e.flatMap(t=>{let n=JS(t.module);return n===void 0?[]:ph(n,`package ${t.name}`)})}async function QS(e){let t=await YS(e.pmRoot),n=XS(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Cc(e,t){let n=await QS(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(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as ZS}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 eE(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(Ys(t));for(let i of n){let a=i.split("."),s=o;for(let p of a){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: ${i}. Select a declared inline object path.`,d.USAGE);s=u[p]}if(gs(s)===null)throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,d.USAGE);let c=r,m=o;for(let p of a.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,a.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return Le(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
2
  `}function fh(e,t,n,r){return{client:t,isItemNotFoundError:o=>Ti(o)&&o.exitCode===d.NOT_FOUND,getItemAt:(o,i)=>uf(o,i,{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,i,a)=>hf(o,i,a),validateRelationshipEvents:o=>{let i=new ff(o.nodes,{registry:Ic(o.definitions)});return o.events.map(a=>i.append({...a,expectedVersion:i.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 i=o.dryRun===!0?await Mu(e,()=>A(e)):await A(e);try{let a=await ii({pmRoot:e,filePath:ne(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${ZS("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:n??C(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async s=>{let c=s===null?null:JSON.parse(s),m=ti(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(!ti(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=eE(f,u,o.replaceSubtrees);let _=ti(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 a.changed&&o.dryRun!==!0&&await Y({path:ne(e),scope:"project",op:"extension:pm:settings"}),{changed:a.changed,dry_run:o.dryRun===!0,replayed:a.replayed===!0,...a.result===void 0?{}:{preview:a.result}}}finally{Fu(e)}}}}import tE from"node:fs/promises";import X from"node:path";import nE from"node:readline/promises";import{stdin as rE,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]="ffab1407-659d-5bc4-95ff-5efe52baf522")}catch{}})();var Oc=Symbol.for("pm.sdk.init-invocation-cwd");var oE=()=>nE.createInterface({input:rE,output:De});function iE(){return structuredClone(At)}var aE=["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: ${aE.join(", ")}`,d.USAGE)}function sE(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 cE(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:X.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function lE(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=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&&Rc(n)){let m=X.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let i=E(e,t.path),a=X.join(X.resolve(e),".agents","pm"),s=X.dirname(X.dirname(i)),c=X.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:X.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function dE(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 mE(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 pE(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 uE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fE(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(uE).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function _E(e,t,n){let r=zo(t.schema),o=pt(e,r.files.types,mt.types),i=fp(await J(o)),a=[],s=[];for(let c of yp(n)){let m=_p(i,c);i=m.file,(m.replaced?s:a).push(m.definition.name)}return await We({pmRoot:e,filePath:o,raw:qo(i),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:s,file:o}}async function hE(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 gE(e,t,n){if(!t||n||await j(X.join(e,"settings.json"))||!await hE(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 yh(e,t){let n=[],r=[];for(let o of t){let i=o?X.join(e,o):e,a=await j(i);await tE.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await Y({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function yE(e,t){let n=oE();try{De.write(`pm init setup wizard (agent-optimized)
3
3
  `),De.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
4
4
 
@@ -20,7 +20,7 @@ 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
20
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 AT=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??[],i=o.filter(m=>m.kind==="blocked_by"),a=e.blocked_reason!==void 0,s=[];if(r&&(delete e.blocked_by,s.push("blocked_by")),a&&(delete e.blocked_reason,s.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let m=new Set(i),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}`]:[],...i.length>0?[`closed_removed_predecessors:${e.id}:${i.map(m=>m.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${i.length}`]:[]]};let c=[...new Set([...n?[n]:[],...i.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 TT=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function CT(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 TT){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},i=r.map(s=>`--${s.key.replaceAll("_","-")}`),a=["--pm-path",t,"update",e.id,...r.flatMap((s,c)=>[i[c],o[s.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:Zt(a),suggested_retry_args:a}}async function IT(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let i=o.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),o=(await e(i))?.duplicate_of}return!1}function RT(e){return typeof e!="string"||e.trim().length===0}async function OT(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 i=x(t,O()),a=new Map,s=async m=>{if(a.has(m))return a.get(m)??null;let p=await K(e,m,t.id_prefix,t.item_format,i.type_to_folder);if(!p)return a.set(m,null),null;let{document:u}=await ae(p,{schema:t.schema});return a.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 IT(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 xT(e,t,n){return e.filter(r=>r.parent===t&&!re(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function PT(e,t,n){let r=new Map(e.map(s=>[s.id.trim().toLowerCase(),s])),o=af(e),i=t.trim().toLowerCase(),a=n.blocked_statuses;return e.filter(s=>a.has(s.status)).map(s=>({item:s,blockerIds:o.get(s.id.trim().toLowerCase())})).filter(({blockerIds:s})=>s.includes(i)).filter(({blockerIds:s})=>s.every(c=>{if(c===i)return!0;let m=r.get(c);return m!==void 0&&re(m.status,n)})).map(({item:s,blockerIds:c})=>({id:s.id,blocker_ids:c})).sort((s,c)=>s.id.localeCompare(c.id))}async function NT(e,t,n,r,o,i){let a=PT(n,r,i),s=[];for(let c of a)try{let m=await se({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 g=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(g)});p.metadata.status=i.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 LT(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:i}of r){if(typeof o!="string")continue;let a=o.trim();a.length!==0&&(e[i]=a,n.push(i))}return n}function $T(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:i}of r)RT(e[o])&&(e[o]=i,n.push(o));return n}function FT(e,t,n,r){let o=[];if(t!=="off"){let i=lg(e);if(i.length>0){let a=i.map(s=>s.label);if(t==="strict"){let s=i.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 ${a.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}:${a.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 MT(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function DT(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function UT(e,t){if(re(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=LT(e,t.options),r=$T(e,t.duplicateOf),o=FT(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let a=["status","closed_at",...i?["completed_at"]:[],...MT(e,t.closeReason),...n];if(rf(e)&&(e.plan_mode="completed",a.push("plan_mode")),t.duplicateOf!==void 0){a.push("duplicate_of");for(let c of r)a.includes(c)||a.push(c)}a.push(...DT(e));let s=Hc(e,t.lifecyclePolicy);return a.push(...s.changedFields),o.push(...s.warnings),{changedFields:a,...o.length>0?{warnings:o}:{}}}async function mg(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),a=$(i.schema),s=C(n.author,i.author_default),c=x(i,O()).type_to_folder,m=await K(o,e,i.id_prefix,i.item_format,c);if(!m)throw await _t(o,e,i.id_prefix,c);let p=await OT(o,i,n.duplicateOf,m.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??i.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Kc({explicit:t,duplicateOf:p,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,_=CT(n.validateClose)??i.governance.close_validation_default,h=await _e(o,i.item_format,c,void 0,i.schema),g=xT(h,m.id,a),y=k(),w=n.completedAt===void 0?y:ie(n.completedAt,new Date(y),"completed-at"),b=await se({pmRoot:o,settings:i,id:m.id,op:"close",author:s,message:n.message,force:n.force,mutate(T){return UT(T.metadata,{pmRoot:o,statusRegistry:a,force:n.force,options:n,duplicateOf:p,validateCloseMode:_,activeChildIds:g,closeReason:f,closedAt:y,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 NT(o,i,h,m.id,s,a)]}}function wt(e,t,n,r){return mg(e,t,n,r)}import GT 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 jT(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 qT(e,t,n,r){let o=await tn(e,t,n,r),i=o.located?await Ku({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function KT(e,t){let n=_r(e),r=_r(t),o=GT.compare(n,r),i=new Set;for(let a of o){if(a.path==="/body"||a.path.startsWith("/body/")){i.add("body");continue}let s=a.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(s.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((a,s)=>a.localeCompare(s))}async function zT(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 HT(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:ug(t),originalRaw:null}}function BT(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 VT(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await te(e.existingItemPath,e.resolvedOriginalRaw),await Bc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await te(e.existingItemPath,e.resolvedOriginalRaw);return}await Bc.rm(e.restoredItemPath,{force:!0})}async function WT(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 i=await A(o),a=x(i,O()),s=await qT(o,e,i,a.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=jT(t,p),f=Yu(Zs(p,u.historyIndex),u),_=Nu(f,{schema:i.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,i,p):null)?.raw??null,g=C(n.author,i.author_default),y=await Te(o,c,i.locks.ttl_seconds,g,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:w,existingItemPath:b}=await zT({pmRoot:o,subject:s,settings:i,typeRegistry:a,historyRawBeforeLock:m,currentItemRawBeforeLock:h,history:p}),S="toon",T=HT(w,p),L=BT({document:T.document,author:g,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),P=KT(T.document,_),M=await yr({pmRoot:o,settings:i,operation:"restore",author:g,before:T.document,after:_});await Wo({pm_root:o,operation:"restore",before:T.document,after:_,changed_fields:P,sdk:ki({pmRoot:o,settings:i,typeToFolder:a.type_to_folder})});let q=Ve(_,{format:S,schema:i.schema}),H=dt(o,_.metadata.type,c,S,a.type_to_folder),Z=await $t(o,g),le=[];try{await te(H,q),b&&H!==b&&await Bc.rm(b);let ue=$e({nowIso:k(),author:g,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,ue)}catch(Ze){throw await VT({existingItemPath:b,resolvedOriginalRaw:T.originalRaw,restoredItemPath:H}),Ze}le=await Ft({pmRoot:o,preferredFormat:i.item_format,typeToFolder:a.type_to_folder,schema:i.schema,itemPath:H,previousItemPath:b??void 0,document:_})}finally{await Z()}let de=await WT({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,...le,...de]}}finally{await y()}}(function(){try{var e=typeof window<"u"?window:typeof 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",YT=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function JT(e,t){return Cr(e,t,{includePagination:!1})}function XT(e,t){return Cr(e,t)}function QT(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 ZT(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 eC(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 tC(e,t){let n=$(t.schema),r=x(t,O()),o=await _e(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,a=new Map;for(let s of o){if(typeof s.parent!="string"||s.parent.length===0||(a.set(s.id,s.parent),re(s.status,n)))continue;let c=i.get(s.parent);c?c.push(s.id):i.set(s.parent,[s.id])}for(let s of i.values())s.sort((c,m)=>c.localeCompare(m));return{childrenByParent:i,parentByChild:a}}function fg(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),a=[],s=new Set,c=!1;for(;i!==void 0&&!s.has(i);){let m=n?.get(i);if(m!==void 0){o+=m+1;break}s.add(i),a.push(i),o+=1,i=t.get(i)}if(i!==void 0&&s.has(i)&&(c=!0),!c){n?.set(e,o);for(let[m,p]of a.entries())n?.set(p,o-m-1)}return o}async function nC(e){let t=await ci(e.pmRoot,Vc,e.rollbackId,_g),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await li(t.items,(o,i)=>an(o,i,{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 rC(e,t,n,r,o){return e.map(i=>{let a=(t.get(i.id)??[]).filter(c=>!n.has(c)),s=!hg(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:s?"skip":"close",...s?{skip_reason:"already_terminal"}:{},...a.length>0?{active_child_ids:a}:{}}})}async function oC(e){let t=await si(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 iC(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 aC(e){return typeof e.rollback=="string"?e.rollback:void 0}function sC(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(XT(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function cC(e){if(!JT(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${YT}). Refusing to match every item.`,d.USAGE)}function lC(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=fg(o.id,t,n)-fg(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function hg(e,t,n){return n||!re(e.status,t)}function dC(e,t,n){return new Set(e.filter(r=>hg(r,t,n)).map(r=>r.id))}async function mC(e){cC(e.options);let t=$(e.settings.schema),n=eC(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ht(e.options.status,ZT(e.options.list),e.global),{childrenByParent:i,parentByChild:a}=await tC(e.pmRoot,e.settings),s=lC(o.items,a),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=dC(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:rC(s,i,u,t,r)}}function pC(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 uC(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 oC({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,i=aC(e);if(QT(e.list),i!==void 0)return sC(e,i),nC({pmRoot:n,rollbackId:i,options:e,global:t});let a=await mC({pmRoot:n,settings:r,options:e,global:t});if(o)return pC(a);let s=new Set(a.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=k(),m=ai(Vc,c),p=await uC({context:a,options:e,closableIds:s,checkpointId:m,nowValue:c}),u={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:a.validateCloseMode,force:a.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await iC({matched:a.matched,closableIds:s,reason:a.reason,closeOptions:u,global:t}),h=f.filter(w=>w.status==="closed").length,g=f.filter(w=>w.status==="skipped").length,y=f.filter(w=>w.status==="failed").length;return{...en({applied:h,skipped:g,failed:y,unmatched:a.unmatchedIds?.length??0}),mode:"apply",matched_count:a.matched.length,dry_run:!1,...a.reason!==void 0?{reason:a.reason}:{},filters:a.listed.filters,...a.validateCloseMode?{validate_close:a.validateCloseMode}:{},...p?{checkpoint:p}:{},closed_count:h,skipped_count:g,failed_count:y,rows:f,ids:_,...a.unmatchedIds!==void 0?{unmatched_ids:a.unmatchedIds,unmatched_count:a.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 fC(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 _C(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),i=x(o,O()),a=await K(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await _t(r,e,o.id_prefix,i.type_to_folder);let s=await ae(a,{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:i.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 g=Tt(O()),y=rt({metadata:h,body:s.document.body},{schema:o.schema,extensionFieldNames:g}),w=await qn({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.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=fC(y.metadata,y.body),S=dt(r,y.metadata.type,u,o.item_format,i.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,q;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:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let Z=await K(r,u,o.id_prefix,o.item_format,i.type_to_folder);if(Z)throw new l(`Cannot copy to ${u}: an item with that id already exists at ${Z.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${u} already exists at ${Z.itemPath}.`,recovery:{suggested_retry:`pm copy ${a.id}`}});await te(S,Ve(y,{format:o.item_format,schema:o.schema,extensionFieldNames:g}));try{let le=$e({nowIso:m,author:p,op:"create",before:P,after:y,message:_C(a.id,t.message)});await xt(T,le)}catch(le){throw await En(S),le}q=await Ft({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:S,document:y})}finally{await H()}M=[...await Y({path:S,scope:"project",op:"create",item_id:y.metadata.id,item_type:y.metadata.type,before:P,after:y,changed_fields:b}),...await Y({path:T,scope:"project",op:"create:history",item_id:y.metadata.id,item_type:y.metadata.type,before:P,after:y,changed_fields:b})],In({id:y.metadata.id,op:"create",item_type:y.metadata.type,status:y.metadata.status,current:Qt(y.metadata,b),changed_fields:b})}finally{await L()}return{source_id:a.id,item:structuredClone(y.metadata),changed_fields:b,warnings:[...Pi(w),...q,...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 hC="hierarchy-integrity";async function Ji(e){let t=e.required?await Te(e.pmRoot,hC,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 Xi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Qi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Zi(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(ao.includes(t))return t;let n=fe(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 ea(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 gC=new Set(["none","null"]);function ta(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 Je(e){return e===void 0?!1:gC.has(e.trim().toLowerCase())}function na(e,t,n){if(!Je(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=>Je(o)))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ra(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(i=>typeof i=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(o.some(i=>Je(i))){if(o.filter(i=>!Je(i)).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 yC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function yg(e,t,n,r){if(yC.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"],wC=new Set(vt);function wg(e){return di(e,vt)}function oa(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!wC.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[a]=i}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,...i}=n;return{...i,command:i.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"]),sa=/^[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 i=o.indexOf("=");if(i<=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 a=o.slice(0,i).trim(),s=o.slice(i+1);if(!sa.test(a))throw new l(`${t} env_set key "${a}" is invalid`,d.USAGE);if(ln.has(a.toUpperCase()))throw new l(`${t} env_set key "${a}" is reserved for sandbox safety`,d.USAGE);r[a]=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(!sa.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 ca(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 la(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(i){throw new l(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,d.USAGE)}return r}}function da(e,t){if(!e)return;let n=fe(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 ma(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 i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function pa(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 i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.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 "${a}" must be numeric`,d.USAGE);r[a]=c}return Object.keys(r).length>0?r:void 0}var vC=new Set(vt);function ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!vC.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw t(`provides key "${o}" more than once after case normalization`);n[a]=i}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 ia(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(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(a=>a.length>0);return i.length>0?i:void 0}function bg(e,t,n){let r=ia(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`)}return r}}function aa(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 kC(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:aa(n,"timeout_seconds",t),i=r===void 0?void 0:aa(r,"timeout",t);if(o!==void 0&&i!==void 0&&o!==i)throw t("timeout and timeout_seconds must match when both are provided");let a=o??i;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function SC(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 EC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ua(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,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!sa.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]=i}return Object.keys(r).length>0?r:void 0}function AC(e,t){let n=ia(e,"env_clear",t);if(n){for(let r of n){if(!sa.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 TC(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 CC(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=aa(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 IC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ua(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,i]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 i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(i)}return Object.keys(r).length>0?r:void 0}function RC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ua(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,i]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]=aa(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function OC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!ua(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${vt.join(", ")}.`);let o=bC(e,r),i=sn(o,"command",r),a=sn(o,"cmd",r);if(i!==void 0&&a!==void 0&&i!==a)throw r("command and cmd must match when both are provided");let s=i??a;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:SC(o,r),timeout_seconds:kC(o,r),pm_context_mode:m,workspace_context_mode:p,env_set:EC(o,r),env_clear:AC(o,r),shared_host_safe:TC(o,"shared_host_safe",r),assert_stdout_contains:ia(o,"assert_stdout_contains",r),assert_stdout_regex:bg(o,"assert_stdout_regex",r),assert_stderr_contains:ia(o,"assert_stderr_contains",r),assert_stderr_regex:bg(o,"assert_stderr_regex",r),assert_stdout_min_lines:CC(o,r),assert_json_field_equals:IC(o,r),assert_json_field_gte:RC(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(i){throw new l(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. 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((i,a)=>OC(i,o.length>1?`entry ${a+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],fa=[{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 _a(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(Je(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let i=e.resolveDefinition(o);if(!i)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(i.metadataKey),n.add(i.optionKey)}return{metadataKeys:t,optionKeys:n}}function ha(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let i of o){if(i.allow_unset===!1)continue;let a=new Set;if(typeof i.key=="string"&&i.key.length>0&&a.add(i.key.toLowerCase()),typeof i.metadata_key=="string"&&i.metadata_key.length>0&&a.add(i.metadata_key.toLowerCase()),typeof i.cli_flag=="string"&&i.cli_flag.length>0&&(a.add(i.cli_flag.replaceAll("-","_").toLowerCase()),a.add(i.cli_flag.toLowerCase())),Array.isArray(i.cli_aliases))for(let s of i.cli_aliases)typeof s!="string"||s.length===0||(a.add(s.replaceAll("-","_").toLowerCase()),a.add(s.toLowerCase()));if(a.has(r))return{optionKey:i.key,metadataKey:i.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 xC(e,t){return t==="defined"?e!==void 0:!!e}function Eg(e,t,n){if(!xC(e,n))return;let r=fe(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function PC(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 NC(e){return Array.from(new Set(Xc(e).map(t=>xe(t.toLowerCase(),Hd,"event weekday")))).sort((t,n)=>ds(t)-ds(n))}function LC(e){return Array.from(new Set(Xc(e).map(t=>{let n=fe(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 $C(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(),i=e.recur_interval?.trim(),a=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,i,a,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(i,"recur_interval",r),_=Eg(a,"recur_count",r),h=PC(s,t,n),g=NC(c),y=LC(m),w=$C(p,n);return{freq:u,interval:f,count:_,until:h,by_weekday:g.length>0?g:void 0,by_month_day:y.length>0?y: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 ae(e,{schema:t})).document.metadata.created_at}async function FC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await K(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Ig(n,t.schema)}function MC(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 DC(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:i})=>i===null?[]:[[o,i]])),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 i=await FC(o,e.context);if(i!==void 0)for(let a of t){let s=r.get(a.id),c=Date.parse(i),m=Date.parse(s);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw MC({holder:o,dependency:a,sourceCreatedAt:i,targetCreatedAt:s,registry:e.registry})}}}async function pn(e){let t=e.registry??Mt(),n=(e.dependencies??[]).filter(a=>!Qp(a.source_kind)),r=[...new Set(n.map(a=>a.id))],o=await Promise.all(r.map(async a=>({target:a,located:await K(e.pmRoot,a,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:a})=>a===null).map(({target:a})=>a).sort((a,s)=>a<s?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${i.length===1?"":"s"} not found: ${i.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:i,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 ${i.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:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await DC({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(a=>`dependency_target_unresolved:${a}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var UC={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 GC(e){return UC[e]}function Qc(e){return GC(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.",jC="--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).",qC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,KC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,xg=1e3,Zc=60*xg,zC=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 HC(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"),i=qC.exec(r);if(i){let c=i[1]==="-"?-1:1,m=Number.parseInt(i[2],10)*c;return Og(n.getTime()+m*Zc,r)}let a=KC.exec(r);if(a){let[,c,m,p,u]=a;if(m||p||u){let f=c==="-"?-1:1,_=Number.parseInt(m??"0",10),h=Number.parseInt(p??"0",10),g=Number.parseInt(u??"0",10),y=_*zC+h*Zc+g*xg;return Og(n.getTime()+f*y,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(jC,d.USAGE);if(n){let i=HC(e,n);if(i<e)throw new l(Rg,d.USAGE);return i===e?void 0:i}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 BC=["at","date","text","title"],VC=["start","date","end","duration","title","description","location","timezone","all_day",...Tg],WC=["key","value"];function Ng(e,t){return t==="trimmed"?e?.trim():e}function YC(e,t){return t==="defined"?e!==void 0:!!e}function ga(e,t,n){return e.map(r=>{let o=me(r,"--reminder");Ye(o,"--reminder",BC);let i=Ng(o.at??o.date,n.valueMode),a=Ng(o.text??o.title,n.valueMode);if(!i||!a)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let s=a.trim();if(!s)throw new l("--reminder text must not be empty",d.USAGE);return{at:ie(i,t,"reminder.at"),text:s}})}function ya(e,t,n){return e.map(r=>{let o=me(r,"--event");Ye(o,"--event",VC);let i=(o.start??o.date)?.trim();if(!i)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let a=ie(i,t,"event.start"),s=o.end?.trim(),c=o.duration?.trim(),m=Pg(a,s,c,t),p=o.title,u=o.description,f=o.location,_=o.timezone,h=p?.trim(),g=u?.trim(),y=f?.trim(),w=_?.trim(),b=[["title",p,h],["description",u,g],["location",f,y],["timezone",_,w]];for(let[P,M,q]of b)if(M!==void 0&&!q)throw new l(`--event ${P} must not be empty`,d.USAGE);let S=o.all_day?.trim(),T=Cg(o,a,t,n.recurrenceEmptyNumericGuard),L=YC(S,n.allDayEmptyGuard)?Ag(S,"--event all_day"):void 0;return{start_at:a,end_at:m,title:h,description:g,location:y,all_day:L,timezone:w,recurrence:T}})}function wa(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,i;if(r.includes(",")||r.includes(`
21
21
  `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=me(r,"--type-option");Ye(a,"--type-option",WC),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),s=r.indexOf(":"),c=a;if(a<=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(),i=r.slice(c+1).trim()}if(!o||!i)throw new l("--type-option requires key and value",d.USAGE);t[o]=i}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]="d979a65f-8e7c-511f-b683-8faa3e43e100")}catch{}})();var JC=["strict","progressive"],XC=["lightweight"],Mg=new Set(["Reminder","Meeting","Event"]),QC=new Set(["author","created_at","text"]),tl=[...Sg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...fa],ZC=(()=>{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})(),va=new Map(tl.map(e=>[e.optionKey,e.canonical])),e0=tl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function t0(e,t){let n=ee(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 n0(e,t){let n=e.default_status;if(n!==void 0){let r=ee(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 r0=ta();function Dg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i};Je(t.template)&&(t.template=void 0);let r=new Set([...va.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Je(i))continue;let a=o==="rank"?"order":va.get(o)??o;n(a),t[o]=void 0}return Ie(e,ra(t,r0))}function ve(e){if(e!==void 0)return e}function o0(e,t){return _a({raw:e,supportedFields:e0,resolveDefinition:n=>ZC.get(n)??ha(n,"create",t)})}var Lg=["id","kind","type","author","created_at","source_kind"],ba=["path","scope","note"];function i0(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 i=o.trim(),a=ka(i,Lg);Dr(i,a);let s=a?me(o,"--dep"):{id:i,kind:"related"};a&&Ye(s,"--dep",Lg);let c=ve(s.id),m=a0(ve(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(ve(s.source_kind)),u=ve(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 a0(e){return typeof e=="string"?mo(e)??e.trim():e}function ka(e,t){return di(e,t)?!0:ui(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 i=o.trim(),a=()=>{if(i.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:i}},s;try{s=me(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return a();throw m}if(Object.keys(s).filter(m=>!QC.has(m)).length>0)return{created_at:el(s.created_at,n),author:ve(s.author)??r,text:i};let c=s.text??"";if(c==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:el(s.created_at,n),author:ve(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=ka(n,ba);Js(n,"--file","file path",r);let o=r?me(t,"--file"):{path:n};if(r&&Ye(o,"--file",ba),!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:ve(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=ka(n,vt);Js(n,"--test","test command",r);let o=r?oa(me(t,"--test"),"--test"):{command:n},i=ve(o.command),a=ve(o.path);if(!i)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let s=ve(o.timeout_seconds),c=ve(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:i,path:a,scope:xe(o.scope??"project",ct,"test scope"),timeout_seconds:m?fe(m,"timeout_seconds"):void 0,pm_context_mode:la(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:ca(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:da(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:ma(o.assert_json_field_equals,"--test"),assert_json_field_gte:pa(o.assert_json_field_gte,"--test"),note:ve(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=ka(n,ba),o=r?me(t,"--doc"):{path:n};if(r&&Ye(o,"--doc",ba),!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:ve(o.note)}}),explicitEmpty:!1})}function s0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:ga(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function c0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Oe(e,"--event","Use --clear-events to clear linked events."),{values:ya(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function l0(e,t,n,r=[]){let o=[...so.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(o))}function d0(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 m0(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 p0(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 u0(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 f0(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Qc(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Ae("create",i)))].sort((i,a)=>i.localeCompare(a));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function _0(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:wa(e),explicitEmpty:!1})}async function h0(e){return await fi(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 g0(e){return ft(e)?await h0(e):e}function y0(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: ${JC.join(", ")}`,d.USAGE)}function w0(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: ${XC.join(", ")}`,d.USAGE)}function v0(e,t,n){let r=y0(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 b0(e,t,n,r,o){let i=e.name,a=m0(t),s=p0(e,n),c=Tn(e,"create",s);if(c.errors.length>0)throw new l(c.errors.join("; "),d.CONFLICT);u0(c.disabled,a,r,i),f0(c.required,n,r);let m=u=>u==="author"&&o!=="unknown"||u==="status"&&e.default_status!==void 0||r.has(u)&&Qc(u)?!0:Ug(a,u),p=c.required.filter(u=>!m(u));return[...new Set(p.map(u=>Ae("create",u)))].sort((u,f)=>u.localeCompare(f))}var Gg=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function k0(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 S0(e,t){return e.filter(n=>{let r=n.match(Gg);return!r||r[2]!==t})}function E0(e,t,n,r){let o=S0(e,t);if(o.length===0)return;let i=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:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function A0(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function T0(e,t,n){let r=e.split("/")[0];switch(r){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"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function jg(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],a=[...new Set([...i,...t])],s=new Set(["--title","--description","--type"]);for(let c of a){if(s.has(c))continue;let m=Kg[c];o.push(...m?[m]:T0(c,e.name,r)),s.add(c)}for(let c of n){let m=A0(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function il(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 C0(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 I0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function R0(){let e=O();return e?e.commands.some(t=>t.action==="templates-show"||I0(t.command)==="templates show"):!1}function O0(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,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[o]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[o]=[...i];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function x0(e,t,n){if(!R0())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 O0(r.result,e)}function V(e,t,n){return e.has(t)||n===void 0?void 0:ve(n)}function un(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var P0=new Set(["milestone","meeting","reminder","event"]);function qg(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,a=r!==void 0&&r.length>0;return P0.has(e.toLowerCase())&&!o&&!i&&!a}function N0(e,t,n,r,o){let i=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),qg(e,n,r,o)&&i.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)`),i}async function L0(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await ni(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function $0(e,t,n,r,o,i){let a=Ei(yi(o),t.id_prefix);if(Qo(a))return{parent:a,warnings:[]};if(vi(r,a,t.id_prefix),await K(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let s=ze(a,t.id_prefix);return{parent:a,warnings:wi(s,i).warnings}}async function F0(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await $0(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function M0(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=ze(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 i=V(e,t,n);if(i===void 0)return{value:void 0,warnings:[]};let a=bi(r,i,o);return{value:a.value,warnings:a.warnings}}async function D0(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:a,statusExplicit:s,nowValue:c,author:m}=e,p=e.dependencyValues;if(i===void 0)return{dependencyValues:p,status:a};let u=ze(i,n.id_prefix),f=await K(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:p,status:a};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:a};let _=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((h,g)=>h.localeCompare(g))[0]??o.open_status;return{dependencyValues:p,status:_}}function U0(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&&ke(r,n)){e.type=r;return}ke("Task",n)&&(e.type="Task")}function G0(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 j0(e,t,n,r,o){let i=e,a=[];if(i.template!==void 0){let h=i.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let g=await x0(h,t,n);i=Dg(C0(g,i))}if(i.type===void 0&&U0(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let s=ke(i.type,o);if(!s){let h=Vu(i.type),g=h?ke(h,o):void 0;if(g)a.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,s=g;else throw new l(Rt(i.type,o.types,Ot(n,r.schema)),d.USAGE)}let c=po(s,o);if(!c)throw new l(`Invalid type value "${i.type}"`,d.USAGE);let m=c.name,p=G0(c,i),u=p.map(h=>`${h.key}=${String(i[h.key])}`);if(u.length>0){i.typeOption=[...u,...i.typeOption??[]];for(let h of p)delete i[h.key]}let f=w0(i.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 _=v0(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:a}}function q0(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 i of o)if(i.enabled){if(i.values&&i.values.length>0)throw new l(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,d.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function K0(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 i=va.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ae("create",r)}`,d.USAGE)}}function z0(e){let t=(n,r)=>{let o=va.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;na(n,Ae("create",r),i)};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 H0(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 Kg={"--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 B0(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:a,createMode:s,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let g=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} ${g}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),p=[jg(n,r,o,i),...m.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${a}" 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 '+a+").")];s==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Mg.has(a)&&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 g=h.split(" ",1)[0],y=Kg[g];return y?[y]:[]}))];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 "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${a} ${h} ...`),p],nextSteps:u,recovery:s==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function V0(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 W0(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=>fe(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function Y0(e,t,n,r,o,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let a=e!==t.close_status?void 0:r.completedAt===void 0?i:ie(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:a,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:a,warnings:[]}}async function J0(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:a,extensionFieldNames:s,afterDocument:c,beforeDocument:m,historyMessage:p,changedFields:u,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,g=dt(t,n,r,o.item_format,i.type_to_folder),y=tt(t,r),w=Mt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(P=>w.resolve(P.kind)?.hierarchy),S=await Ji({pmRoot:t,author:a,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,a,!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 _e(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0,q=await K(t,r,o.id_prefix,o.item_format,i.type_to_folder);if(q)throw new l(`Item "${r}" already exists`,d.CONFLICT,{code:"item_already_exists",id:q.id,path:q.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${q.id}.`]});if(M){let de=$(o.schema);Ai(M,[...M,c.metadata],r,qe=>re(qe,de),w)}let H=await yr({pmRoot:t,settings:o,operation:"create",author:a,before:null,after:c});await Wo({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:ki({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let Z=await $t(t,a,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),le=[];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 te(g,Ve(c,{format:o.item_format,schema:o.schema,extensionFieldNames:s}));try{let de=$e({nowIso:f,author:a,op:"create",before:m,after:c,message:p,context:H.decisions.length===0?void 0:{workflow_policies:H.decisions}});await xt(y,de)}catch(de){throw await En(g),de}T&&(await S(),T=!1),le=await Ft({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:g,document:c})}finally{await Z()}L=[...H.warnings,...M?Gi(M,[...M,c.metadata],r):[],...le,...await Y({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:u}),...await Y({path:y,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 g0(e)),r=E(process.cwd(),t.path);await I(r);let o=await A(r),i=$(o.schema),a=nt(o.schema),s=x(o,O()),c=await j0(n,t,r,o,s);n=c.resolvedOptions;let{typeDefinition:m,type:p,createMode:u}=c,f=o0(n.unset,a),{explicitUnsets:_,clearOptionKeys:h}=q0(n,f);K0(n,f),z0(n);let g=C(ve(n.author),o.author_default),y=b0(m,n,u,h,g),w=k(),b=i0(n.dep,w,o.id_prefix,g),S=fn("--comment",n.comment,w,g),T=fn("--note",n.note,w,g),L=fn("--learning",n.learning,w,g),P=nl(n.file),M=rl(n.test);M.values=await zn(M.values,g,w);let q=ol(n.doc),H=s0(n.reminder,w),Z=c0(n.event,w),le=_0(n.typeOption),de=rr(p,le.values,s),qe=O(),G=Tt(qe),ue=co(n.field,qe),Ze=gu(n,a,p),Za=new Set(Ze.missing_required_flags),es=a.definitions.filter(W=>Za.has(`--${W.cli_flag}`));H0(ue,Ze,f);let tr=k0(de.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));B0({combinedMissingFlags:Zr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:tr,openStatus:i.open_status,type:p,createMode:u,missingRequiredRuntimeFields:es}),E0(de.errors,p,m,i);let Ke=await M0({pmRoot:r,settings:o,typeRegistry:s,explicitId:n.id}),St=n.status!==void 0?t0(n.status,i):n0(m,i),eo=n.priority!==void 0?Fn(n.priority):2,R=f.metadataKeys,Ht=V0(R,n),bn=un(R,"deadline",n.deadline,W=>ie(W,new Date(w),"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=W0(R,n),to=V(R,"goal",n.goal),_b=V(R,"objective",n.objective),hb=V(R,"value",n.value),gb=V(R,"impact",n.impact),yb=V(R,"outcome",n.outcome),wb=V(R,"why_now",n.whyNow),vb=V(R,"assignee",n.assignee),bb=R.has("author")?void 0:ve(n.author)??g,kb=V(R,"parent",n.parent),Cd=await L0(kb,n,R,r),rs=Cd.parent,Sb=Cd.parentSource,Eb=V(R,"reviewer",n.reviewer),Ab=un(R,"risk",n.risk,W=>xe(Xi(W),kn,"risk")),Tb=un(R,"confidence",n.confidence,W=>Zi(W)),Cb=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Id=o.validation.sprint_release_format,Bt=[...c.warnings,...N0(p,Ke,bn,H.values,Z.values)],Rd=await F0({itemId:Ke,parent:rs,pmRoot:r,settings:o,typeRegistry:s,policy:Cb});rs=Rd.parent,Bt.push(...Rd.warnings);let Od=Fg(R,"sprint",n.sprint,"sprint",Id),Ib=Od.value;Bt.push(...Od.warnings);let xd=Fg(R,"release",n.release,"release",Id),Rb=xd.value;Bt.push(...xd.warnings);let Pd=V(R,"blocked_by",n.blockedBy),Nd=await D0({pmRoot:r,settings:o,typeRegistry:s,statusRegistry:i,blockedBy:Pd,dependencyValues:b.values,status:St,statusExplicit:n.status!==void 0,nowValue:w,author:g}),os=Nd.dependencyValues;Ur(Ke,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:Ke,createdAt:w}],schema:o.schema})),St=Nd.status;let Ob=V(R,"blocked_reason",n.blockedReason),xb=V(R,"unblock_note",n.unblockNote),Pb=V(R,"reporter",n.reporter),Nb=un(R,"severity",n.severity,W=>xe(Qi(W),Sn,"severity")),Lb=V(R,"environment",n.environment),$b=V(R,"repro_steps",n.reproSteps),Ld=V(R,"resolution",n.resolution),Fb=V(R,"expected_result",n.expectedResult),Mb=V(R,"actual_result",n.actualResult),Db=V(R,"affected_version",n.affectedVersion),Ub=V(R,"fixed_version",n.fixedVersion),Gb=V(R,"component",n.component),jb=un(R,"regression",n.regression,W=>ea(W)),qb=V(R,"customer_impact",n.customerImpact),is=il(n.title,"--title"),as=n.description??"",no=n.body??"",$d=await qn({title:is,description:as,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(...Pi($d));let ss=Y0(St,i,o,n,Ld,w),Kb=ss.closeReason,zb=St===i.close_status?w:void 0,Hb=ss.completedAt;Bt.push(...ss.warnings);let ro=qs({id:Ke,title:is,description:as,type:p,type_options:de.normalized,status:St,closed_at:zb,completed_at:Hb,close_reason:Kb,priority:eo,tags:Ht,created_at:w,updated_at:w,deadline:bn,assignee:vb,author:bb,estimated_minutes:Et,acceptance_criteria:ts,definition_of_ready:et,order:ns,goal:to,objective:_b,value:hb,impact:gb,outcome:yb,why_now:wb,parent:rs,reviewer:Eb,risk:Ab,confidence:Tb,sprint:Ib,release:Rb,blocked_by:Pd,blocked_reason:Ob,unblock_note:xb,reporter:Pb,severity:Nb,environment:Lb,repro_steps:$b,resolution:Ld,expected_result:Fb,actual_result:Mb,affected_version:Db,fixed_version:Ub,component:Gb,regression:jb,customer_impact:qb,dependencies:os,comments:S.values,notes:T.values,learnings:L.values,files:P.values,tests:M.values,docs:q.values,reminders:H.values,events:Z.values,...ue,...Ze.values});try{lo(ro,qe)}catch(W){throw new l(W instanceof Error?W.message:"Invalid extension item field values",d.USAGE)}let Bb=rt({metadata:ro,body:no},{schema:o.schema,extensionFieldNames:G}),Vb={metadata:{},body:""},Fd=[..._].sort((W,cs)=>W.localeCompare(cs)),Wb=d0(n.message,Fd),Md=l0(ro,no,Fd,[...Object.keys(ue),...Object.keys(Ze.values??{})]),Yb=await J0({pmRoot:r,type:p,id:Ke,settings:o,typeRegistry:s,author:g,extensionFieldNames:G,afterDocument:Bb,beforeDocument:Vb,historyMessage:Wb,changedFields:Md,nowValue:w,similarityCandidate:{title:is,description:as,body:no},allowDuplicate:n.allowDuplicate}),Dd=structuredClone(ro);u==="strict"&&_.has("dependencies")&&(Dd.dependencies=[]);let Jb=yg(Ke,p,St,i);return qg(p,bn,H.values,Z.values)&&Xp(`[pm] warning: ${p} '${Ke}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ke} --deadline <ISO>' or 'pm update ${Ke} --event "start=<ISO>,end=<ISO>"'.`),{item:Dd,changed_fields:Md,warnings:[...Bt,...Yb],...Object.fromEntries([["parent_source",Sb],["next_transition",Jb],["similarity_advisory",$d]].filter(W=>W[1]!==void 0))}}import Sa 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),i=C(t.author,o.author_default),a=await ef({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),s=a.targetPath?Sa.relative(r,a.targetPath).split(Sa.sep).join("/"):void 0;return{item:a.item,changed_fields:a.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:a.item.status,...s?{target_path:s}:{},history_retained:Sa.relative(r,tt(r,a.item.id)).split(Sa.sep).join("/"),tombstone_retention:"retain_append_only",warnings:a.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 X0(e){await I(e)}async function sl(e,t,n){let r=E(process.cwd(),n.path);if(await X0(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 ji({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 ni(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 Q0(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),i=x(o,O()),a=await K(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await _t(r,e,o.id_prefix,i.type_to_folder);let s=ze(a.id,o.id_prefix),c=await ae(a,{schema:o.schema}),m=zg(c.document.metadata.title);return await _u(r,s),await ji({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 Q0(e,t){let n=await A(e),r=x(n,O()),o=await K(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await ae(o,{schema:n.schema});return zg(i.document.metadata.title)}function zg(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 Ea(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,...fa],Z0=(()=>{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})(),Aa=new Map(ml.map(e=>[e.optionKey,e.canonical])),eI=ml.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),tI=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),nI=ta({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Qg(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i},r=new Set([...Aa.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Je(i))continue;let a=o==="rank"?"order":Aa.get(o)??o;n(a),t[o]=void 0}return Ie(e,ra(t,nI))}function Zg(e,t,n=[]){return _a({raw:e,supportedFields:eI,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return Z0.get(r)??ha(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var Hg=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 Bg(e){let t=e.disallowedFlags.flatMap(r=>{let o=Hg.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=Hg.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 rI(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 i=(c,m,p)=>{c&&p.push(m)};if(o){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(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 Bg({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 a=[];i(t.status!==void 0,"--status",a),i(t.closeReason!==void 0,"--close-reason",a),i(t.assignee!==void 0,"--assignee",a),i(t.parent!==void 0,"--parent",a),i(t.blockedBy!==void 0,"--blocked-by",a),i(t.blockedReason!==void 0,"--blocked-reason",a),i(t.unblockNote!==void 0,"--unblock-note",a),i(t.dep!==void 0,"--dep",a),i(t.depRemove!==void 0,"--dep-remove",a),i(t.replaceDeps===!0,"--replace-deps",a),i(t.replaceTests===!0,"--replace-tests",a),i(t.replaceFiles===!0,"--replace-files",a),i(t.replaceDocs===!0,"--replace-docs",a),i(t.note!==void 0,"--note",a),i(t.learning!==void 0,"--learning",a),i(t.test!==void 0,"--test",a),i(t.reminder!==void 0,"--reminder",a),i(t.event!==void 0,"--event",a),i(t.clearDeps===!0,"--clear-deps",a),i(t.clearComments===!0,"--clear-comments",a),i(t.clearNotes===!0,"--clear-notes",a),i(t.clearLearnings===!0,"--clear-learnings",a),i(t.clearFiles===!0,"--clear-files",a),i(t.clearTests===!0,"--clear-tests",a),i(t.clearDocs===!0,"--clear-docs",a),i(t.clearReminders===!0,"--clear-reminders",a),i(t.clearEvents===!0,"--clear-events",a);let s=[...n].filter(c=>tI.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...s),a.length>0)throw Bg({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: ${a.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:a})}function oI(e,t){let n=ee(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 iI(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=ee(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ee(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 aI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:ey(e)}function ey(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 sI=["id","kind","type","author","created_at","source_kind"],cI=["id","kind","type","author","created_at","source_kind"];function ty(e){return e.startsWith("```")||e.includes(`
22
22
  `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:ui(e)}function ny(e){return typeof e=="string"?mo(e)??e.trim():e}function Ca(e,t,n,r){return e?(Oe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=ty(i);Dr(i,a);let s=a?me(o,"--dep"):{id:i,kind:"related"};a&&Ye(s,"--dep",sI);let c=s.id?.trim(),m=ny((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:aI(s.created_at,n),author:u??r,source_kind:p??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function lI(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=ty(r);if(Dr(r,o,"--dep-remove"),o){let i=me(r,"--dep-remove");Ye(i,"--dep-remove",cI);let a=i.id?.trim();if(!a)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(a.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${a}"`,d.USAGE);let s=ny(Wn(i.kind??i.type)),c=vr(Wn(i.source_kind)),m=Wn(i.author),p=Wn(i.created_at);return{id:br(a,t,c),kind:s?xe(s,Vt,"dependency kind","kind"):void 0,source_kind:c,author:m,created_at:p?ey(p):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:ze(r,t)}})):[]}function Ta(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function dI(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),i=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function mI(e,t,n,r){let o=[...e??[]],i=!1;if(t===void 0){let a=o.filter(s=>s.kind!=="blocked_by");return a.length!==o.length&&(o=a,i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(a=>a.kind==="blocked_by"&&a.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function pI(e,t,n,r,o,i){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let s=await K(n,ze(a,r),r,o,i);return s?{id:s.id}:{unresolved:a}}function uI(e,t,n,r,o){let i=mI(e.dependencies,t,n,r);i.changed&&(i.dependencies===void 0?delete e.dependencies:e.dependencies=i.dependencies,o.includes("dependencies")||o.push("dependencies"))}function fI(e){return`${e.path}::${e.scope}`}function _I(e){return`${e.path}::${e.scope}`}function hI(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function ry(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 Vg(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 gI(e,t,n){let r=new Set,o=(i,a)=>{a&&r.add(i)};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 i=Zg(e.unset,t,n);for(let a of i.optionKeys)o(a,!0)}return r}function yI(e,t,n,r,o){let i=po(e,n);if(!i)throw new l(`Invalid type value "${e}"`,d.USAGE);let a=Tn(i,"update",[]);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);let s=gI(t,r,o);for(let c of a.disabled)if(s.has(Vg(c,e)))throw new l(`Option ${Ae("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of a.required)if(!s.has(Vg(c,e)))throw new l(`Missing required option ${Ae("update",c)} for type "${e}"`,d.USAGE)}var wI=new Set(["order","rank"]),vI=ws.filter(e=>!wI.has(e)),oy=["tags","closeReason",...vI],bI=["title","description","body","status","closeReason","completedAt","priority","type",...ws,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],kI=[{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"}],SI=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>xe(Xi(e),kn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Zi(e)}],EI=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>xe(Qi(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=>ea(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function dl(e,t,n){for(let r of e){let o=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!i)){if(i){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 AI(e){return Qg(await fi(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 AI(e):Qg(e)}function TI(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 CI(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 II(e){let t={};for(let n of oy)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function RI(e,t){let n=II(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=Aa.get(r)??r;throw new l(`Cannot combine --unset ${i} 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 OI(e){let t=(n,r)=>{let o=Aa.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;na(n,Ae("update",r),i)};for(let n of oy)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 xI(e,t){let n={};for(let r of bI)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 PI(e){let t=await K(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 ae(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function NI(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return _e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function LI(e){e.before&&Ai(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>re(t,e.statusRegistry),Mt())}function $I(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 FI(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Ei(yi(e.options.parent),e.settings.id_prefix);if(Qo(t))return{resolvedParentValue:t,warnings:[]};if(vi(e.id,t,e.settings.id_prefix),await K(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=ze(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:wi(n,e.parentReferencePolicy).warnings}}function MI(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function DI(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await K(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 ae(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ke(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=iI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function UI(e){if(!e.fieldFlags.status||ee(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let t=Object.entries(e.fieldFlags).filter(([a,s])=>s&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),n=[],r=[];if(t.length>0){let a=Ie(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),s=await at(e.id,a,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),i=[...e.workflowTransitionWarnings,...n,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...r,...o.changed_fields],warnings:i}}function GI(e,t,n,r){return t.title!==void 0&&(e.metadata.title=il(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")),ee(e.metadata.status,n)??e.metadata.status}var jI=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function qI(e,t){for(let n of jI)e[n]!==void 0&&(delete e[n],t.push(n))}function KI(e,t,n,r,o){let i=oI(n,t.statusRegistry);if(e.metadata.status=i,o.push("status"),i===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}!re(i,t.statusRegistry)&&re(r,t.statusRegistry)&&qI(e.metadata,o)}function zI(e,t,n,r){if(t.options.status!==void 0&&KI(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!re(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 HI(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&&re(n,t.statusRegistry)&&!re(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function BI(e,t,n,r){zI(e,t,n,r),HI(e,t,n,r)}function VI(e,t,n){let r=ke(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=ke(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 yI(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),WI(e,t,r,n),r}function WI(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 i=wa(t.options.typeOption??[]),a=rr(n,i,t.typeRegistry);if(a.errors.length>0)throw new l(a.errors.join("; "),d.USAGE);e.metadata.type_options=a.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 YI(e,t){let n=new Set(t.map(o=>Ta(o))),r=new Set;return e.filter(o=>{if(!n.has(Ta(o)))return!0;let i=dI(o);return r.has(i)?!1:(r.add(i),!0)})}function JI(e,t,n){let r=t.filter(o=>!e.some(i=>ry(i,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 XI(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=YI(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>Ta(i)));for(let i of t.dependencyUpdates.additions){let a=Ta(i);o.has(a)||(r.push(i),o.add(a))}}t.dependencyRemovals.length>0&&(JI(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>ry(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function QI(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,i){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function ZI(e,t,n){Wg(e,"files",t.options.file,t.fileUpdates.values,fI,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),eR(e,t,n),Wg(e,"docs",t.options.doc,t.docUpdates.values,_I,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Wg(e,t,n,r,o,i,a,s){if(!(n===void 0&&!a.has(t))){if(i)e.metadata[t]=r;else if(a.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 eR(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Yg(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Yg([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Yg(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=hI(r);n.has(o)||(t.push(r),n.add(o))}return t}function tR(e,t,n){let r=t.options.addTags,o=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let a=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Pt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=pi(Ln(a,r),o),n.changedFields.push("tags")}dl(kI,t.options,n),rR(e,t,n.changedFields)}function nR(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 i=mi(Nn(e.metadata.acceptance_criteria),r,o);if(i.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.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 a=i.criteria.join("; ");e.metadata.acceptance_criteria!==a&&(a===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=a,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function rR(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=fe(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function oR(e,t,n,r){iR(e,t,n.changedFields),aR(e,t,n.changedFields),dl(SI,t.options,n),Jg(e,t,"sprint",r,n.changedFields),Jg(e,t,"release",r,n.changedFields),sR(e,t,n.changedFields),dl(EI,t.options,n)}function iR(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 aR(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 Jg(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 i=bi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function sR(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)&&uI(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function cR(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=ga(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=ya(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function lR(e,t,n){Xg(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Xg(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let a=o.replaceAll("_","-"),s=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===o)?.cli_flag??a;throw new l(`Cannot combine --unset ${a} with --${s}`,d.USAGE)}Le(e[o],i)||(e[o]=i,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,i]of Object.entries(r))Le(e[o],i)||(e[o]=i,n.push(o))}function Xg(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function dR(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let i=t[o];return i!==void 0&&(!Array.isArray(i)||!Le(i,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 mR(e,t){dR(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],a=GI(e,t.options,t.statusRegistry,o),s=e.metadata,c={metadataRecord:s,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};BI(e,t,a,o),VI(e,t,o),XI(e,t,o),QI(e,t,o),ZI(e,t,o),tR(e,t,c),nR(e,t,c),oR(e,t,c,i),(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),ee(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),cR(e,t,o),lR(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")&&i.push(`acceptance_criteria_replaced:${Nn(n.acceptance_criteria).length}:${Nn(m.acceptance_criteria).length}`),{changedFields:p,warnings:i}}async function iy(e,t,n,r={}){t=await pl(t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),a=$(i.schema),s=nt(i.schema),c=O(),m=Tt(c),p=x(i,c),u=i.governance.workflow_enforcement??"off",f=u==="off"?[]:Cp(i.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][i.validation.parent_reference],h=Zg(t.unset,s,m),g=new Set(h.optionKeys),y=new Set(h.metadataKeys);ul(t),CI({definitions:TI(t),options:t,clearOptionKeys:g,clearItemMetadataKeys:y}),rI(e,t,y),RI(t,h),OI(t);let w=C(t.author,i.author_default),b=new Date,S=b.toISOString(),T=Ca(t.dep,i.id_prefix,S,w);Ur(e,T.additions);let L=await pn({pmRoot:o,dependencies:T.additions,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:p.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:i.schema}),P=lI(t.depRemove,i.id_prefix),M=fn("--comment",t.comment,S,w),q=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(R=>({...R,author:w}))}:M,H=fn("--note",t.note,S,w),Z=fn("--learning",t.learning,S,w),le=nl(t.file),de=rl(t.test);de.values=await zn(de.values,w,S);let qe=ol(t.doc),G=[],ue=await FI({id:e,options:t,unsetTargets:h,pmRoot:o,settings:i,typeRegistry:p,parentReferencePolicy:_}),Ze=await pI(t.blockedBy,y.has("blocked_by"),o,i.id_prefix,i.item_format,p.type_to_folder),Za=Ze.id,es=[...ue.warnings,...MI(Ze)],tr=oi(t,s,t.runtimeFieldCommands),zt=xI(t,tr);if(!Object.values(zt).some(Boolean))return PI({pmRoot:o,id:e,settings:i,typeRegistry:p});G.push(...await DI({options:t,fieldFlags:zt,workflowEnforcement:u,typeWorkflows:f,statusRegistry:a,typeRegistry:p,pmRoot:o,id:e,settings:i}));let Zr=await UI({options:t,fieldFlags:zt,statusRegistry:a,workflowTransitionWarnings:G,global:n,id:e});if(Zr)return Zr;$I(t);let Ke=Mt(),St=zt.parent&&!y.has("parent")||T.additions.some(R=>Ke.resolve(R.kind)?.hierarchy),eo=await Ji({pmRoot:o,author:w,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:St});try{let R=await NI({fieldFlags:zt,clearedMetadataKeys:y,pmRoot:o,settings:i,typeToFolder:p.type_to_folder}),Ht,bn,Et=await Zu({pmRoot:o,settings:i,typeToFolder:p.type_to_folder,id:e,op:pR(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=uR({document:et,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:a}),bn=Ht?{recurrence:Ht}:void 0,R=R?.map(to=>to.id===et.metadata.id?structuredClone(et.metadata):to);let ns=mR(et,{options:t,settings:i,typeRegistry:p,statusRegistry:a,runtimeFieldRegistry:s,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:y,dependencyUpdates:T,dependencyRemovals:P,commentUpdates:q,noteUpdates:H,learningUpdates:Z,fileUpdates:le,testUpdates:de,docUpdates:qe,resolvedParentValue:ue.resolvedParentValue,resolvedBlockedByDependencyId:Za,runtimeFieldUpdates:tr,nowValue:b,nowIso:S,author:w,pmRoot:o});return LI({before:R,document:et,statusRegistry:a}),ns}});await eo();let ts=R?Gi(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 pR(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function uR(e){if(e.recurrenceReason===void 0)return;let t=ee(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!re(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=ee(n,e.statusRegistry)??n,o=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(a=>{let s=o[a];return typeof s=="string"?[[a,s]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function at(e,t,n){return iy(e,t,n)}async function ay(e,t,n,r){let o=await iy(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 i=E(process.cwd(),r.path),a=$((await A(i)).schema),s=a.open_status,c=Ea(a),m=n.status??s,p=ee(m,a)??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 sy(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 cy="no_available_next_item";function ly(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 i=await A(o),a=$(i.schema),s=C(r.author,i.author_default),c=Pn(s),m=null,p=!1,u=[],f=await se({pmRoot:o,settings:i,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let h=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||h;if(m=h.trim().length>0?h:null,kp(_.metadata.status,a)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return p=!0,u.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let b=await sy(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 y={assignee:s,claim_principal:c},w=["assignee","claim_principal"].filter(b=>_.metadata[b]!==y[b]);return Object.assign(_.metadata,y),{changedFields:w,warnings:u}}});return p||await gc({pmRoot:o,settings:i,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 dy(e,t,n={},r={}){let o=fR(n.maxAttempts),i=await A(E(process.cwd(),t.path)),a={...n,author:C(n.author,i.author_default)},s=await Ir({...r,callerAuthor:a.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 _R(c.slice(0,o),e,t,a)}function fR(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 _R(e,t,n,r={},o=Gr){let i=0;for(let s of e){i+=1;try{let c=await o(s.id,t,n,r),m={...c,recommendation:s,attempts:i,available:!0};if(!c.skipped)return m}catch(c){if(!ly(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:i,warnings:[cy]};let a=i===0;throw new l(a?"No actionable items matched the selection filters":"No actionable item remained available to claim",a?d.NOT_FOUND:d.CONFLICT,{code:cy,why:a?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[a?"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 i=await A(o),a=C(r.author,i.author_default),s=Pn(a),c=r.ownershipReleaseBypass===!0,m=null,p;try{p=await se({pmRoot:o,settings:i,id:e,op:"release",author:a,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=$(i.schema),f=js(p.item.status,u)===js(u.in_progress_status,u);return{item:p.item,released_by:a,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]="69182e8d-b8c7-5b70-8650-185a8f07f6ee")}catch{}})();async function _l(e,t,n){try{return await n()}catch(r){let o=r instanceof l?r.context:{},i=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 i.cause=r,i}}async function hl(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start cannot be combined with --next or --if-available for an explicit item",d.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await A(E(process.cwd(),n.path)),o=Ea($(r.schema)),i=await Gr(e,t.force===!0,n,t),a=i.item.id,s=await _l(a,"claim",()=>at(a,Dt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:a,action:"start_task",claim:i,update:s}}async function gl(e,t,n){let r=await A(E(process.cwd(),n.path)),o=$(r.schema).open_status,i=await at(e,Dt(t,{status:o},["assignee","pause"]),n),a=i.item.id,s=await _l(a,"update",()=>jr(a,t.force===!0,n,t));return{id:a,action:"pause_task",update:i,release:s}}async function yl(e,t,n,r){let o=await wt(e,t,n,r),i=o.item.id,a=await _l(i,"close",()=>jr(i,n.force===!0,r,n));return{id:i,action:"close_task",close:o,release:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="140b50c9-b0b3-5446-8ef9-5993bf4d830c")}catch{}})();async function my(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r};if(i.start===!0)return _n(e,"start_task");let a=e.args.next===!0||r.next===!0?await dy(o,e.global,i,i):await Gr(qr(e,r),o,e.global,i);return Ee(a,{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 py(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return r.releaseAssignment===!0?_n(e,"close_task"):Ee(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}=he(e.args,e.options),i=qr(e,o),a=Dt(o,{force:e.force===!0||o.force===!0}),s=t==="start_task"?await hl(i,a,e.global):t==="pause_task"?await gl(i,a,e.global):await yl(i,wl(e,o),a,e.global);return Ee(s,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function uy(e){if(e.options.pause===!0)return _n(e,"pause_task");let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options),o=await jr(qr(e,r),e.force===!0,e.global,r);return Ee(o,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function fy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=he(e.args,e.options);return Ee(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 Ia(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 hR=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],_y=["brief","standard","deep"],yy="plan-step-",Al="draft",El=["bug-investigation","feature-implementation","refactoring-sprint"],hy={"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 gR(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(hy,t)?hy[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 yR(e,t){return t>0?Math.round(e/t*100):0}function wy(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 He(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 vy(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 by(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 wR(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 vR(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=_y.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${_y.join(", ")}`,d.USAGE);return n}function bR(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 kR(e,t){let n=e,r={},o=[];for(let i of t){let a=i.startsWith("plan.")?i.slice(5):i;if(a.length!==0){if(!vl.has(a)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,a)&&(r[a]=n[a])}}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 i=o.indexOf("=");if(i<=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,i).trim().toLowerCase()]=o.slice(i+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 SR(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=yR(t.completed,t.total),t}function ER(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${yy}${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),i=e.find(a=>a.order===o);if(i)return i}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function gy(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 AR(e,t){let n=t.filter(a=>a.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 a of e.slice().sort((s,c)=>s.order-c.order)){let s=gy(a);if(s){o.push({from_step:a.id,...s});continue}r.push(a)}return{targets:r,skipped:o}}let i=new Set;for(let a of t){let s=Yn(e,a);if(i.has(s.id))continue;i.add(s.id);let c=gy(s);if(c){o.push({from_step:s.id,...c});continue}r.push(s)}return{targets:r,skipped:o}}function TR(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 CR(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function IR(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((a,s)=>a.order-s.order),r=SR(n),o=CR(n),i={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:IR(n),linked_items:(e.dependencies??[]).map(a=>({id:a.id,kind:a.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function 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 ky(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 RR(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function Sy(e,t){let n=x(e.settings,O()),r=await K(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 ae(r,{schema:e.settings.schema});return ky(o.document.metadata),{document:o.document,itemId:r.id}}function OR(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of He(e.related))t.push(`id=${n},kind=related`);for(let n of He(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of He(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function xR(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 PR(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||He(e.dependsOn).length>0||He(e.link).length>0}function NR(e){let t=e.stepTitle?.trim()||void 0,n=wy(e.step),r=e.template?.trim()?gR(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function LR(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 $R(e,t){let n=Tl(e.stepStatus,"pending"),r=xl(e,"depends_on"),o=Pe(e.file).map(Il),i=Pe(e.test).map(Rl),a=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:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n==="completed"?s:void 0}}function FR(e){let t=NR(e),n=PR(e);if(LR(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[$R(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,i)=>({id:`${yy}${String(i+1).padStart(3,"0")}`,order:i+1,title:o,body:t.templateSteps[i]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Ey(e,t,n=[]){Ie(e,t),n.length>0&&ju(t,n)}async function MR(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=vy(e.mode,Al),i=wR(e.harness),a=e.fromSearch?.trim(),s=xR(e),{steps:c,hasPerStepDetailOptions:m}=FR(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:OR(e),message:e.message??(a?`plan create (search: ${a})`:"plan create")};Ey(e,f);let _=await Gt(f,t),h=await se({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(y){let w=["plan_mode"];y.metadata.plan_mode=o,i&&(y.metadata.plan_harness=i,w.push("plan_harness"));let b=e.scope?.trim();b&&(y.metadata.plan_scope=b,w.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(y.metadata.plan_resume_context=S,w.push("plan_resume_context")),y.metadata.plan_steps=c,w.push("plan_steps"),s&&(y.metadata.plan_validation=[...y.metadata.plan_validation??[],s],w.push("plan_validation")),u&&(y.metadata.assignee=u,w.push("assignee")),{changedFields:w}}}),g=Ue(h.item,"brief");return{action:"create",plan:g,step:c[0],next_actions:Ge(_.item.id,g),warnings:[..._.warnings],generated_at:k()}}async function DR(e,t,n){let r=vR(t.depth),o=bR(t.fields),{document:i,itemId:a}=await Sy(n,e),s=Ue(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?s:kR(s,o),next_actions:Ge(a,s),warnings:[],generated_at:k()}}function UR(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 se({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){ky(o.metadata);let i=$(e.ctx.settings.schema);if(re(o.metadata.status,i)||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 a=(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(a,o);n=c.resultStep;let m=a.slice().sort((u,f)=>u.order-f.order).map((u,f)=>({...u,order:f+1}));o.metadata.plan_steps=m;let p=UR(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 GR(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"),i=t.allowMultipleActive===!0,{document:a,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;Ay(p,void 0,o,i);let f=jR(p,t,{order:u,title:r,status:o});return p.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Ue(a.metadata,"standard");return{action:"add-step",plan:m,step:s,next_actions:Ge(c,m),warnings:[],generated_at:k()}}function Ay(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(i=>i.id!==t&&i.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 jR(e,t,n){let r=xl(t,"depends_on"),o=Pe(t.file).map(Il),i=Pe(t.test).map(Rl),a=Pe(t.doc).map(Ol),s=k();return{id:ER(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:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n.status==="completed"?s:void 0}}function xl(e,t){let n=He(e.dependsOn).map(p=>({id:p,kind:t})),r=He(e.related).map(p=>({id:p,kind:"related"})),o=He(e.blocks).map(p=>({id:p,kind:"blocks"})),i=He(e.blockedBy).map(p=>({id:p,kind:"blocked_by"})),a=He(e.link),s=by(e.linkKind,t),c=e.linkNote?.trim(),m=a.map(p=>{let u={id:p,kind:s};return c&&(u.note=c),u});return[...n,...r,...o,...i,...m]}async function bl(e,t,n,r){let{document:o,resultStep:i,itemId:a}=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 Ay(c,p.status==="in_progress"?p.id:void 0,f,_),qR(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:i,next_actions:Ge(a,s),warnings:[],generated_at:k()}}function qR(e,t,n,r){KR(e,t,n),zR(e,t),e.status=n,e.updated_at=r,HR(e,n,r)}function KR(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 zR(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),i=Pe(t.doc).map(Ol);r.length>0&&(e.files=kl(e.files,r)),o.length>0&&(e.tests=kl(e.tests,o)),i.length>0&&(e.docs=kl(e.docs,i))}function kl(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let i=JSON.stringify(o);r.has(i)||(r.add(i),n.push(o))}return n}function HR(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function BR(e,t,n,r,o){let{document:i,itemId:a,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(i.metadata,"standard");return{action:"reorder-step",plan:c,step:s,next_actions:Ge(a,c),warnings:[],generated_at:k()}}async function VR(e,t,n,r){let{document:o,itemId:i,resultStep:a}=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:a,next_actions:Ge(i,s),warnings:[],generated_at:k()}}async function WR(e,t,n,r){let o=xl(t,by(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 i=t.promoteToItemDep===!0,{document:a,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=y=>`${y.kind}:${y.id}`,g=new Set(_.map(h));for(let y of o){let w=h(y);g.has(w)||(_.push(y),g.add(w))}if(f.linked_items=_,f.updated_at=k(),i){let y=u.metadata.dependencies??[],w=S=>`${S.kind}:${S.id}`,b=new Set(y.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))||(y.push(L),b.add(w(L)))}u.metadata.dependencies=y}return{changedSteps:[f.id],resultStep:f}}}),m=Ue(a.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ge(s,m),warnings:[],generated_at:k()}}async function YR(e,t,n,r){let o=He(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:i,itemId:a,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(i.metadata,"standard");return{action:"unlink",plan:c,step:s,next_actions:Ge(a,c),warnings:[],generated_at:k()}}async function Sl(e,t,n,r){let o=TR(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 i=C(t.author,n.settings.author_default),{document:a,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:i,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:i,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(a.metadata,"deep");return{action:r,plan:c,next_actions:Ge(s,c),warnings:[],generated_at:k()}}async function JR(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:i}=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:[]}}}),a=Ue(o.metadata,"brief");return{action:"resume",plan:a,next_actions:Ge(i,a),warnings:[],generated_at:k()}}async function XR(e,t,n){let r=vy(t.mode??"approved","approved"),{document:o,itemId:i}=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:[]}}}),a=Ue(o.metadata,"brief");return{action:"approve",plan:a,next_actions:Ge(i,a),warnings:[],generated_at:k()}}function Ty(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function QR(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:Ty(t),generated_at:k()}}function ZR(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let i=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${i}`)}return r}async function eO(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Pe(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let c=a.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 i={...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:ZR(e.parent,e.planItemId,o)};Ey(e.options,i,["description",...Object.keys(n)]);let a=await Gt(i,{path:e.pmRoot});t.push({id:a.item.id,title:a.item.title,type:e.resolvedTypeName,parent:a.item.parent,tags:a.item.tags??[],from_step:o.id})}return t}function tO(e,t,n){for(let r of t){let o=n.find(s=>s.from_step===r.id);if(!o)continue;let i=e.find(s=>s.id===r.id);if(!i)continue;let a=i.linked_items??[];a.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=a,i.updated_at=k()}}async function nO(e,t,n){let r=He(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",i=x(n.settings,O()),a=ke(o,i);if(!a)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let s=t.materializeParent?.trim()||e,c=t.materializeTags,m=await Sy(n,e),p=(m.document.metadata.plan_steps??[]).slice(),{targets:u,skipped:f}=AR(p,r);if(u.length===0){if(f.length>0)return QR(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await eO({targets:u,parent:s,planItemId:m.itemId,resolvedTypeName:a,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:g}=await st({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return tO(w,u,_),{changedSteps:u.map(b=>b.id)}}}),y=Ue(h.metadata,"standard");return{action:"materialize",plan:y,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ge(g,y),warnings:Ty(f),generated_at:k()}}function rO(e){if(e.subcommand==="create")return e;let t=wy(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 oO(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 iO={create:(e,t)=>MR(e.options,e.global,t),show:(e,t)=>DR(bt(e,"show"),e.options,t),"add-step":(e,t)=>GR(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=oO(e);return BR(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=hn(e,"remove-step");return VR(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=hn(e,"link");return WR(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=hn(e,"unlink");return YR(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)=>JR(bt(e,"resume"),e.options,t),approve:(e,t)=>XR(bt(e,"approve"),e.options,t),materialize:(e,t)=>nO(bt(e,"materialize"),e.options,t)};function aO(e){let t=iO[e];if(!t)throw Ce({command_path:"plan",token:e,allowed:hR});return t}async function Cy(e){let t=await RR(e.global),n=rO(e),r=await aO(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Ia(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 Ry=1,Nl="update-many",sO=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),cO=["--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(", "),lO={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"},dO=[{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"}],mO={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"},Oy=e=>{let t={};for(let[n,r]of Object.entries(e))sO.has(n)||r!==void 0&&(t[n]=r);return t},pO=e=>Object.keys(Oy(e)).length>0,xy=e=>typeof e=="string"?e.trim():e,uO=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},fO=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??xy(e)},_O={priority:uO,estimatedMinutes:Pl,order:Pl,rank:Pl,regression:fO},hO=(e,t)=>{if(t!==void 0)return(_O[e]??xy)(t)},gO=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return mO[t]??t},Ra=(e,t)=>Le(e,t),yO=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],wO=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,vO=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Iy=(e,t)=>t===void 0?void 0:e[t],Jn=e=>Array.isArray(e)?e.length:0,bO=(e,t,n)=>{let r=n[e.addKey],o=Iy(n,e.removeKey),i=Jn(r),a=Jn(o),s=n[e.clearKey]===!0,c=Iy(n,e.replaceKey)===!0;if(![s,c,i>0,a>0].includes(!0))return;let m=yO(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:vO({replace:c,clear:s,removeCount:a}),clear:s,replace:c,add_count:i,remove_count:a,before_count:wO(e.field,m)}}},kO=(e,t)=>{let n=[];for(let r of dO){let o=bO(r,e,t);o!==void 0&&n.push(o)}return n},SO=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],EO=(e,t)=>{if(![t.tags!==void 0,Jn(t.addTags)>0,Jn(t.removeTags)>0].includes(!0))return;let n=SO(e.tags),r=t.tags===void 0?n:Pt(t.tags),o=Ln(r,t.addTags),i=pi(o,t.removeTags).slice().sort((s,c)=>s.localeCompare(c)),a=n.slice().sort((s,c)=>s.localeCompare(c));if(!Ra(a,i))return{field:"tags",before:n,after:i}},AO=(e,t)=>{let n=e.acceptance_criteria,r=mi(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(!Ra(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},TO=(e,t,n)=>{for(let[r,o]of Object.entries(lO)){let i=n[r];if(i===void 0)continue;let a=t[o],s=hO(r,i);Ra(a,s)||e.push({field:o,before:a,after:s})}},CO=(e,t,n,r)=>{let o=oi(n,r,["update_many"]);for(let[i,a]of Object.entries(o)){let s=t[i];Ra(s,a)||e.push({field:i,before:s,after:a})}},IO=(e,t,n)=>{for(let r of n??[]){let o=gO(r),i=t[o];i!==void 0&&e.push({field:o,before:i,after:null})}},RO=(e,t,n={})=>{let r=e,o=[],i=EO(r,n);if(i&&o.push(i),TO(o,r,n),Jn(n.addAc)>0||Jn(n.removeAc)>0){let a=AO(r,n);a!==void 0&&o.push(a)}return o.push(...kO(r,n)),CO(o,r,n,t),IO(o,r,n.unset),{id:e.id,changes:o}},OO=(e,t)=>Bu(e,t,{strict:!0,flagLabel:"--filter-status"}),xO=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)},PO=[({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(!ke(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&&!ee(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")}],NO=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of PO)i(o)},LO=async e=>{let t=await ci(e.pmRoot,Nl,e.rollbackId,Ry),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await li(t.items,(o,i)=>an(o,i,{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}},$O=async e=>{let t={schema_version:Ry,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 si(e.pmRoot,Nl,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},FO=(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},MO=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)}},DO=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 LO({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},UO=async e=>{OO(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 i=RO(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,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:FO(e.options.list?.ids,r)}},GO=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)}),jO=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)}),qO=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!o.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let a=Xs({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),s=await at(i.id,a,e.global);t.push({id:i.id,status:"updated",changed_fields:s.changed_fields,warnings:s.warnings}),n.push(i.id)}catch(a){t.push({id:i.id,status:"failed",error:An(a)})}}return{rows:t,updatedIds:n}},KO=async e=>{if(e.plan.actionable.length===0)return jO(e.plan);let t=k(),n=ai(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})),i=e.options.checkpoint===!1?void 0:await $O({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}),a=await qO({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),s=u=>a.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,...i?{checkpoint:i}:{},updated_count:c,skipped_count:m,failed_count:p,rows:a.rows,ids:a.updatedIds,...Ll(e.plan)}},Py=async(e,t)=>{let n=await MO(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Xs(await pl(e.update))});let o=Oy(e.update);if(xO(e.list),r!==void 0)return DO({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!pO(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${cO}), or pass --dry-run for a filter-only preview.`,d.USAGE);NO(e.update,n.settings,n.statusRegistry,n.pmRoot),ul(e.update);let i=await pn({pmRoot:n.pmRoot,dependencies:Ca(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}),a=await UO({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:i});return await pn({pmRoot:n.pmRoot,dependencies:Ca(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:a.listed.items.map(s=>({id:s.id,createdAt:s.created_at})),schema:n.settings.schema}),e.dryRun===!0?GO(a):KO({runtime:n,options:e,global:t,plan:a})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6263346a-08ee-5eb9-81b9-47e933793c07")}catch{}})();function zO(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 HO(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 BO(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 Ny(e,t,n){let r=zO(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 i=r===void 0?void 0:Yt(r),a=[t.since,t.eventType].some(h=>h!==void 0),s=BO(t.since),c=gr(t.limit),m=await Bn(e,{...t,...a?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,a].includes(!0)},n,{input:await Wi(i===void 0?t:{add:i},"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:HO(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 g=[h.format==="json",h.data!==void 0].every(Boolean),y=[s===void 0,Date.parse(h.created_at)>=(s??Number.POSITIVE_INFINITY)].includes(!0),w=[!p,h.event_type===p].includes(!0);return[!a,[g,y,w].every(Boolean)].includes(!0)}),f=a?Pc(u,c):u,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...a?{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 ix from"node:path";import VO from"node:fs/promises";import Ly 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 WO="templates",YO=".json",JO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,XO=Zo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),QO=new Set(XO);function ZO(e){let t=e.trim();if(!JO.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 $y(e){return Ly.join(e,WO)}function Fy(e,t){return Ly.join($y(e),`${t}${YO}`)}async function ex(e){await I(e)}function My(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function tx(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(QO.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="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 My(t)}function nx(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,i]of Object.entries(n)){let a=o.trim();if(a.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof i=="string"){r[a]=i;continue}if(Array.isArray(i)&&i.every(s=>typeof s=="string")){r[a]=[...i];continue}throw new l(`Template "${t}" contains invalid value for option "${a}".`,d.GENERIC_FAILURE)}return My(r)}function rx(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=nx(r.options,t),i=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:i,updated_at:typeof r.updated_at=="string"?r.updated_at:i,options:o}}async function ox(e,t){let n=await J(Fy(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return rx(n,t)}async function $l(e,t,n){let r=E(process.cwd(),n.path);await ex(r);let o=ZO(e),i=tx(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let a=k(),s=Fy(r,o),c=a;await j(s)&&(c=(await ox(r,o)).created_at);let m={name:o,created_at:c,updated_at:a,options:i},p=await A(r);return await VO.mkdir($y(r),{recursive:!0}),await We({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 jy=["list","show","apply","lint"],ax="schema-types",sx="schema-statuses",cx="schema-fields";function Oa(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function qy(){let{profiles:e,warnings:t}=wp(Oa());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 Ky(e){let t;try{t=Ko(e,Oa())}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 zy(e){let t;try{t=Ko(e,Oa())}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 lx(e,t){return ix.join(e,"templates",`${t}.json`)}async function dx(e,t){let n=await J(lx(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 Dy(e,t,n,r){let o=new Map;for(let i of r.templates){let a=await dx(e,i.name);a!==void 0&&o.set(i.name,a)}return{typesRaw:await J(pt(e,t.files.types,mt.types)),statusesRaw:await J(pt(e,t.files.statuses,mt.statuses)),fieldsRaw:await J(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 Uy(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(i=>({key:i.type,status:i.status}))),config:Xn(t.config.changes),templates:Xn(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,a)=>i.localeCompare(a)),generated_at:k()}}async function mx(e){await I(e)}function px(e){try{let t=Ko(e,Oa());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Hy(e,t,n){let r=E(process.cwd(),n.path);await mx(r);let o=px(e),i=o.profile,a=o.warnings,s=t.dryRun===!0,c=await A(r),m=zo(c.schema);if(s){let w=await Dy(r,m,c,i),b=Gy(i,w);return Uy(i,b,!1,!0,[...a])}let p=C(t.author,c.author_default),u=Du(c),f=!!t.force,_=[...a],h=[],g=async w=>{h.push(await Te(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(ax),await g(sx),await g(cx);let w=await Dy(r,m,c,i);if(y=Gy(i,w),y.types.changed){let b=pt(r,m.files.types,mt.types);await We({pmRoot:r,filePath:b,raw:qo(y.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(i.types.map(L=>up(L).name)),T=y.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(y.statuses.changed){let b=pt(r,m.files.statuses,mt.statuses);await We({pmRoot:r,filePath:b,raw:Sp(y.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(y.fields.changed){let b=pt(r,m.files.fields,mt.fields);await We({pmRoot:r,filePath:b,raw:vp(y.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(y.config.changed||y.workflows.changed){for(let b of y.config.changes){if(b.status==="unchanged")continue;let S=Bo(b.key);S!==void 0&&Vo(c,S,b.value)}c.schema.type_workflows=y.workflows.result,await Fe(r,c,"profile:apply-config")}for(let b of y.templates.changes)b.status!=="unchanged"&&await $l(b.name,{...b.options},n)}finally{for(let w of h.reverse())try{await w()}catch{}}return Uy(i,y,y.changed,!1,_)}function Gy(e,t){try{return tu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import wx 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 Vy=10,gn="https://schema.unbrained.dev/pm/eval-query-set/v1";var xa={schema:gn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Xe=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},ux=new Set(["keyword","semantic","hybrid"]);function By(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 fx(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=By(r,n),i=Array.from({length:t.size},()=>1),a=By(i,n);return a===0?0:o/a}function _x(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 i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function hx(e,t,n){return n<=0?0:Fl(e,t,n)/n}function gx(e,t,n){return t.size===0?0:Fl(e,t,n)/t.size}function Wy(e,t,n){return{ndcg:fx(e,t,n),mrr:_x(e,t,n),precision:hx(e,t,n),recall:gx(e,t,n),relevant_total:t.size,retrieved_relevant:Fl(e,t,n)}}function Yy(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 yx(e,t){if(typeof e!="object"||e===null)throw new Xe(`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 Xe(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Xe(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new Xe(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new Xe(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!ux.has(n.mode)))throw new Xe(`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 Xe(`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 Xe('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Xe("Eval query set must contain at least one query");return{schema:gn,queries:n.map((r,o)=>yx(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 vx=Dl.join("search","eval-queries.json"),Ul={schema:gn,examples:[JSON.stringify(xa)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},bx=new Set(["keyword","semantic","hybrid"]),kx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!bx.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},Sx=e=>{if(e===void 0||e==="")return Vy;let t=Xd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},Ex=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,Ax=async e=>{try{return await wx.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ul,examples:[`echo '${JSON.stringify(xa)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},Tx=(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)}},Cx=e=>{try{return Ml(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ul)}},Ix=async e=>Cx(Tx(await Ax(e),e)),Rx=async(e,t,n,r)=>{let o=e.mode??t,i=(await Rr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),a=Wy(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:G_(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:jt(a.ndcg),mrr:jt(a.mrr),precision:jt(a.precision),recall:jt(a.recall)}}},Ox=(e,t,n,r)=>{let o=Yy(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(i=>(i.violations?.length??0)===0)}},Jy=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=Sx(e.k),o=kx(e.mode),i=Ex(e.failUnder),a=e.queries?Dl.resolve(process.cwd(),e.queries):Dl.join(n,vx),s=await Ix(a),c=[],m=[];for(let p of s.queries){let{report:u,metrics:f}=await Rx(p,o,r,t);m.push(f),c.push(u)}return Ox(r,c,m,i)};import{readFile as xx,writeFile as Px}from"node:fs/promises";import Nx 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 Xy=["item","history","relationship","json"];function Lx(e){let t=e.trim().toLowerCase();if(Xy.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${Xy.join(", ")}.`,d.USAGE)}function $x(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 xx(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function Fx(e){let t=E(process.cwd(),e.path);return await j(ne(t))?A(t):null}function Mx(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Qy(e,t){let n=Lx(e.artifact),r=$x(e.prefer),o=Nx.resolve(e.outputPath??e.oursPath),[i,a,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_(i,a,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_(i,a,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 Fx(t),h=Mx(e.itemPath??o,_),g=Tt(O()),y=i_(i,a,s,{format:h,schema:_?.schema,extensionFieldNames:g,preferred:r,conflictResolution:"latest_document_update"});if(c=y.merged,p.push(...y.conflict_fields),u.item={fields_from_theirs:y.fields_from_theirs,union_fields:y.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let w=Su(c,{format:h,schema:_?.schema,extensionFieldNames:g}),b=w.metadata,S=[...new Set([...y.fields_from_theirs,...y.union_fields,...y.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:y.fields_from_theirs,unionFields:y.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,n_(T==="body"?w.body:b[T])])),decisions:y.conflict_decisions,operation:await s_(process.cwd(),e.itemPath)}}}else{let _=a_(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await Px(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 Zy(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 Li(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as Dx}from"node:fs/promises";import Ux 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 Gx=4;function ew(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,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,a=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:i,coordinates:a}}async function jx(e,t){let n=[];for(let r of t){let o;try{o=await Dx(Ux.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}let s=f_(a,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 qx(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 Kx(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 zx(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 Hx(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=>Li(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}async function tw(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}),i=ew(o),a=await jx(r,i.coordinates),s=await Ci(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 qx({candidates:a,options:e,global:t}),u=m.receipts,f=await Zy({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(ue=>!_.has(ue.id))){let ue=h.get(G.item_id)??[];ue.push(G),h.set(G.item_id,ue)}let g=Object.fromEntries([...h].map(([G,ue])=>[G,{merge:{receipts:ue.map(nn)}}])),y=Object.fromEntries([...h].map(([G,ue])=>[G,{gitWorkspaceRoot:s,receipts:ue}])),w=await Fi({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:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),b=new Set(w.streams.map(G=>G.id)),S=[...h.keys()].filter(G=>!b.has(G)),T=await Df(S,Gx,G=>Kx({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));zx({receiptOnlyIds:S,results:T,repair:w});let L=await Hx({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),P=await Ui({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),M=p===0?o:await Ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),q=ew(M),H=P.checks.every(G=>G.status==="ok"),Z=n?u.length===0:L+f.length===u.length,le=[w.totals.failed===0,H,Z,q.count===0,!q.truncated].every(Boolean),de=i.truncated||q.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.",de,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:le?["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.",de,...a.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:le,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:L,abandoned:f.length,summaries:u.map(nn),missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:q.count},validation:P,guidance:qe,generated_at:P.generated_at}}import{createHash as Bx}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 ow=1,iw=/^[A-Za-z0-9_-]+$/,Vx=100,nw=1e3;var xH=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Qe(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 Wx(e){return Bx("sha256").update(Yt({type:Qe(e.type),author:Qe(e.author),item:Qe(e.item),harness:Qe(e.harness),agent_instance:Qe(e.agentInstance),provenance:Qe(e.provenanceFilter)})).digest("hex").slice(0,24)}function rw(e,t){let n={version:ow,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 Yx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===ow,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 Jx(e,t){let n=e.trim();if(n.length===0||n.length>4096||!iw.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(!Yx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function Xx(e){let t=e??Vx;if(!Number.isSafeInteger(t)||t<0||t>nw)throw new l(`Mutation event limit must be an integer from 0 to ${nw}.`,d.USAGE,{code:"invalid_event_limit"});return t}function Qx(e,t){let n=e?.trim();if(!n)return{};if(iw.test(n))return{cursor:Jx(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 Zx(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 eP(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 Pa(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=Xx(e.limit),r=eP(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),i=o.agent_identity.identity_vocabulary,a=P_(o.agent_identity.harness_signals),s=N_({provenance:e.provenanceFilter},a),c=Qe(e.harness),m=Wx(e),{cursor:p,sinceTimestamp:u}=Qx(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:Qe(e.type),authors:Qe(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:Qe(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:Qe(e.item),limit:n},_=await Zx(t,f),h=_.events.map(g=>({...r==="row"?{cursor:rw(g,m)}:{},item_id:g.stream_id,version:g.stream_offset+1,ts:g.entry.ts,author:g.entry.author,type:g.entry.op,...g.entry.message===void 0?{}:{message:g.entry.message},patch_count:g.entry.patch.length,...e.full===!0?{entry:g.entry}:{},...e.provenance===!0?{provenance:L_(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:rw(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:$_(_.events.map(g=>g.entry),i,a)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="015a3a52-f631-5ab7-b5c5-10a54a0b750c")}catch{}})();var tP="1h",nP="now",rP="+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 sw(e,t,n,r){let o=aw(e,t,n),i=[];return qt(i,"start",n.start??nP),n.end!==void 0?qt(i,"end",n.end):qt(i,"duration",n.duration??tP),qt(i,"location",n.location),qt(i,"timezone",n.timezone),n.allDay===!0&&qt(i,"all_day","true"),o.event=[i.join(",")],Gt(o,r)}function cw(e,t,n){return sw("Meeting",e,t,n)}function lw(e,t,n){return sw("Event",e,t,n)}function dw(e,t,n){let r=aw("Reminder",e,t),o=[];return qt(o,"at",t.at??rP),qt(o,"text",t.text??e),r.reminder=[o.join(",")],Gt(r,n)}import zr from"node:crypto";import{cp as mw,lstat as oP,mkdir as yn,readFile as Qn,readdir as ql,rename as fw,rm as zl,writeFile as Na}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 _w="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var hw=F.join("runtime","workspace-snapshots"),iP=new Set(["checkpoints","locks","runtime","search","transactions"]),aP=/^[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"}},gw={renameEntry:fw,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 te(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},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 jy=["list","show","apply","lint"],ax="schema-types",sx="schema-statuses",cx="schema-fields";function Oa(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function qy(){let{profiles:e,warnings:t}=wp(Oa());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 Ky(e){let t;try{t=Ko(e,Oa())}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 zy(e){let t;try{t=Ko(e,Oa())}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 lx(e,t){return ix.join(e,"templates",`${t}.json`)}async function dx(e,t){let n=await J(lx(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 Dy(e,t,n,r){let o=new Map;for(let i of r.templates){let a=await dx(e,i.name);a!==void 0&&o.set(i.name,a)}return{typesRaw:await J(pt(e,t.files.types,mt.types)),statusesRaw:await J(pt(e,t.files.statuses,mt.statuses)),fieldsRaw:await J(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 Uy(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(i=>({key:i.type,status:i.status}))),config:Xn(t.config.changes),templates:Xn(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,a)=>i.localeCompare(a)),generated_at:k()}}async function mx(e){await I(e)}function px(e){try{let t=Ko(e,Oa());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Hy(e,t,n){let r=E(process.cwd(),n.path);await mx(r);let o=px(e),i=o.profile,a=o.warnings,s=t.dryRun===!0,c=await A(r),m=zo(c.schema);if(s){let w=await Dy(r,m,c,i),b=Gy(i,w);return Uy(i,b,!1,!0,[...a])}let p=C(t.author,c.author_default),u=Du(c),f=!!t.force,_=[...a],h=[],g=async w=>{h.push(await Te(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(ax),await g(sx),await g(cx);let w=await Dy(r,m,c,i);if(y=Gy(i,w),y.types.changed){let b=pt(r,m.files.types,mt.types);await We({pmRoot:r,filePath:b,raw:qo(y.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(i.types.map(L=>up(L).name)),T=y.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(y.statuses.changed){let b=pt(r,m.files.statuses,mt.statuses);await We({pmRoot:r,filePath:b,raw:Sp(y.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(y.fields.changed){let b=pt(r,m.files.fields,mt.fields);await We({pmRoot:r,filePath:b,raw:vp(y.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(y.config.changed||y.workflows.changed){for(let b of y.config.changes){if(b.status==="unchanged")continue;let S=Bo(b.key);S!==void 0&&Vo(c,S,b.value)}c.schema.type_workflows=y.workflows.result,await Fe(r,c,"profile:apply-config")}for(let b of y.templates.changes)b.status!=="unchanged"&&await $l(b.name,{...b.options},n)}finally{for(let w of h.reverse())try{await w()}catch{}}return Uy(i,y,y.changed,!1,_)}function Gy(e,t){try{return tu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import wx 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 Vy=10,gn="https://schema.unbrained.dev/pm/eval-query-set/v1";var xa={schema:gn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Xe=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},ux=new Set(["keyword","semantic","hybrid"]);function By(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 fx(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=By(r,n),i=Array.from({length:t.size},()=>1),a=By(i,n);return a===0?0:o/a}function _x(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 i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function hx(e,t,n){return n<=0?0:Fl(e,t,n)/n}function gx(e,t,n){return t.size===0?0:Fl(e,t,n)/t.size}function Wy(e,t,n){return{ndcg:fx(e,t,n),mrr:_x(e,t,n),precision:hx(e,t,n),recall:gx(e,t,n),relevant_total:t.size,retrieved_relevant:Fl(e,t,n)}}function Yy(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 yx(e,t){if(typeof e!="object"||e===null)throw new Xe(`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 Xe(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Xe(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new Xe(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new Xe(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!ux.has(n.mode)))throw new Xe(`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 Xe(`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 Xe('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Xe("Eval query set must contain at least one query");return{schema:gn,queries:n.map((r,o)=>yx(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 vx=Dl.join("search","eval-queries.json"),Ul={schema:gn,examples:[JSON.stringify(xa)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},bx=new Set(["keyword","semantic","hybrid"]),kx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!bx.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},Sx=e=>{if(e===void 0||e==="")return Vy;let t=Xd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},Ex=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,Ax=async e=>{try{return await wx.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ul,examples:[`echo '${JSON.stringify(xa)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},Tx=(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)}},Cx=e=>{try{return Ml(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ul)}},Ix=async e=>Cx(Tx(await Ax(e),e)),Rx=async(e,t,n,r)=>{let o=e.mode??t,i=(await Rr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),a=Wy(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:G_(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:jt(a.ndcg),mrr:jt(a.mrr),precision:jt(a.precision),recall:jt(a.recall)}}},Ox=(e,t,n,r)=>{let o=Yy(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(i=>(i.violations?.length??0)===0)}},Jy=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=Sx(e.k),o=kx(e.mode),i=Ex(e.failUnder),a=e.queries?Dl.resolve(process.cwd(),e.queries):Dl.join(n,vx),s=await Ix(a),c=[],m=[];for(let p of s.queries){let{report:u,metrics:f}=await Rx(p,o,r,t);m.push(f),c.push(u)}return Ox(r,c,m,i)};import{readFile as xx,writeFile as Px}from"node:fs/promises";import Nx 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]="932450d7-963b-566b-a5ad-1b577a895e8e")}catch{}})();var Xy=["item","history","relationship","json"];function Lx(e){let t=e.trim().toLowerCase();if(Xy.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${Xy.join(", ")}.`,d.USAGE)}function $x(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 xx(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function Fx(e){let t=E(process.cwd(),e.path);return await j(ne(t))?A(t):null}function Mx(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Qy(e,t){let n=Lx(e.artifact),r=$x(e.prefer),o=Nx.resolve(e.outputPath??e.oursPath),[i,a,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_(i,a,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_(i,a,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 Fx(t),h=Mx(e.itemPath??o,_),g=Tt(O()),y=i_(i,a,s,{format:h,schema:_?.schema,extensionFieldNames:g,preferred:r,conflictResolution:"latest_document_update"});if(c=y.merged,p.push(...y.conflict_fields),u.item={fields_from_theirs:y.fields_from_theirs,union_fields:y.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let w=Su(c,{format:h,schema:_?.schema,extensionFieldNames:g}),b=w.metadata,S=[...new Set([...y.fields_from_theirs,...y.union_fields,...y.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:y.fields_from_theirs,unionFields:y.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,n_(T==="body"?w.body:b[T])])),decisions:y.conflict_decisions,operation:await s_(process.cwd(),e.itemPath,a)}}}else{let _=a_(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await Px(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]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();async function Zy(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 ${n.operation.kind} 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 Li(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as Dx}from"node:fs/promises";import Ux 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 Gx=4;function ew(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,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,a=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:i,coordinates:a}}async function jx(e,t){let n=[];for(let r of t){let o;try{o=await Dx(Ux.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}let s=f_(a,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 qx(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 Kx(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 zx(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 Hx(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=>Li(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}async function tw(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}),i=ew(o),a=await jx(r,i.coordinates),s=await Ci(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 qx({candidates:a,options:e,global:t}),u=m.receipts,f=await Zy({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(ue=>!_.has(ue.id))){let ue=h.get(G.item_id)??[];ue.push(G),h.set(G.item_id,ue)}let g=Object.fromEntries([...h].map(([G,ue])=>[G,{merge:{receipts:ue.map(nn)}}])),y=Object.fromEntries([...h].map(([G,ue])=>[G,{gitWorkspaceRoot:s,receipts:ue}])),w=await Fi({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:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),b=new Set(w.streams.map(G=>G.id)),S=[...h.keys()].filter(G=>!b.has(G)),T=await Df(S,Gx,G=>Kx({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));zx({receiptOnlyIds:S,results:T,repair:w});let L=await Hx({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),P=await Ui({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),M=p===0?o:await Ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),q=ew(M),H=P.checks.every(G=>G.status==="ok"),Z=n?u.length===0:L+f.length===u.length,le=[w.totals.failed===0,H,Z,q.count===0,!q.truncated].every(Boolean),de=i.truncated||q.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.",de,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:le?["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.",de,...a.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:le,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:L,abandoned:f.length,summaries:u.map(nn),missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:q.count},validation:P,guidance:qe,generated_at:P.generated_at}}import{createHash as Bx}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 ow=1,iw=/^[A-Za-z0-9_-]+$/,Vx=100,nw=1e3;var xH=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Qe(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 Wx(e){return Bx("sha256").update(Yt({type:Qe(e.type),author:Qe(e.author),item:Qe(e.item),harness:Qe(e.harness),agent_instance:Qe(e.agentInstance),provenance:Qe(e.provenanceFilter)})).digest("hex").slice(0,24)}function rw(e,t){let n={version:ow,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 Yx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===ow,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 Jx(e,t){let n=e.trim();if(n.length===0||n.length>4096||!iw.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(!Yx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function Xx(e){let t=e??Vx;if(!Number.isSafeInteger(t)||t<0||t>nw)throw new l(`Mutation event limit must be an integer from 0 to ${nw}.`,d.USAGE,{code:"invalid_event_limit"});return t}function Qx(e,t){let n=e?.trim();if(!n)return{};if(iw.test(n))return{cursor:Jx(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 Zx(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 eP(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 Pa(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=Xx(e.limit),r=eP(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),i=o.agent_identity.identity_vocabulary,a=P_(o.agent_identity.harness_signals),s=N_({provenance:e.provenanceFilter},a),c=Qe(e.harness),m=Wx(e),{cursor:p,sinceTimestamp:u}=Qx(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:Qe(e.type),authors:Qe(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:Qe(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:Qe(e.item),limit:n},_=await Zx(t,f),h=_.events.map(g=>({...r==="row"?{cursor:rw(g,m)}:{},item_id:g.stream_id,version:g.stream_offset+1,ts:g.entry.ts,author:g.entry.author,type:g.entry.op,...g.entry.message===void 0?{}:{message:g.entry.message},patch_count:g.entry.patch.length,...e.full===!0?{entry:g.entry}:{},...e.provenance===!0?{provenance:L_(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:rw(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:$_(_.events.map(g=>g.entry),i,a)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="015a3a52-f631-5ab7-b5c5-10a54a0b750c")}catch{}})();var tP="1h",nP="now",rP="+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 sw(e,t,n,r){let o=aw(e,t,n),i=[];return qt(i,"start",n.start??nP),n.end!==void 0?qt(i,"end",n.end):qt(i,"duration",n.duration??tP),qt(i,"location",n.location),qt(i,"timezone",n.timezone),n.allDay===!0&&qt(i,"all_day","true"),o.event=[i.join(",")],Gt(o,r)}function cw(e,t,n){return sw("Meeting",e,t,n)}function lw(e,t,n){return sw("Event",e,t,n)}function dw(e,t,n){let r=aw("Reminder",e,t),o=[];return qt(o,"at",t.at??rP),qt(o,"text",t.text??e),r.reminder=[o.join(",")],Gt(r,n)}import zr from"node:crypto";import{cp as mw,lstat as oP,mkdir as yn,readFile as Qn,readdir as ql,rename as fw,rm as zl,writeFile as Na}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 _w="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var hw=F.join("runtime","workspace-snapshots"),iP=new Set(["checkpoints","locks","runtime","search","transactions"]),aP=/^[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"}},gw={renameEntry:fw,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 te(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
24
24
  `)}};async function yw(e,t=""){let n=await ql(F.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,a)=>i.name.localeCompare(a.name))){if(t.length===0&&iP.has(o.name))continue;let i=F.posix.join(t.replaceAll(F.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await yw(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function ww(e){let t=await yw(e),n=zr.createHash("sha256"),r=[],o=0;for(let a of t){let s=await Qn(F.join(e,a));r.push(s),o+=s.byteLength,n.update(a),n.update("\0"),n.update(String(s.byteLength)),n.update("\0"),n.update(s)}let i=n.digest("hex");return{manifest:{schema:_w,fingerprint:i,files:t,bytes:o},contents:r}}function pw(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
25
25
  `).filter(t=>t.trim().length>0).length}async function sP(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),i=await Promise.all(o.map(async a=>[a,await Qn(F.join(e,a))]));for(let[a,s]of i)n.set(a,s)}return n}function Hl(e){if(!aP.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 vw(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,hw)}function bw(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 kw(e,t){try{return JSON.parse(await Qn(e,"utf8"))}catch(n){throw Be(n)?bw(t):n}}async function uw(e,t,n){try{await zl(e,{recursive:n})}catch(r){throw Be(r)?bw(t):r}}async function cP(e,t,n=gw){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 lP(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(i){throw await r.renameEntry(n,t),await r.removeEntry(e),i}await r.removeEntry(n)}async function dP(e,t){return Hl(t),/^[a-f0-9]{64}$/.test(t)?t:(await kw(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 ww(e),o=wn(e),i=F.join(o,"objects",n.fingerprint),a=!1;try{a=(await oP(i)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&Be(s)))throw s}if(!a){let s=F.join(o,"objects",`.create-${process.pid}-${zr.randomUUID()}`);await vw("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 Na(p,r[c])}await Na(F.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
26
26
  `,"utf8"),await yn(F.dirname(i),{recursive:!0})}),a=await cP(s,i)}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 Na(m,`${JSON.stringify(s,null,2)}