@unbrained/pm-cli 2026.9.29 → 2026.9.30

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 (88) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +9 -0
  3. package/dist/cli/main.js +1 -1
  4. package/dist/cli-bundle/bundle-manifest.json +156 -156
  5. package/dist/cli-bundle/chunks/{chunk-4DOL43PF.js → chunk-6XTJLOKW.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-S5A2UIRV.js → chunk-6YEET7XI.js} +22 -22
  7. package/dist/cli-bundle/chunks/{chunk-U3QJGJYN.js → chunk-A6NDNRCK.js} +3 -3
  8. package/dist/cli-bundle/chunks/{chunk-5KEPG36D.js → chunk-BNAT4EYR.js} +9 -9
  9. package/dist/cli-bundle/chunks/{chunk-OTLIM22J.js → chunk-BTCE36JS.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-SJI55O65.js → chunk-BX4LEJX4.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-GP6QTYSD.js → chunk-EGAIIWI3.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-FYTXVVZG.js +2 -0
  13. package/dist/cli-bundle/chunks/{chunk-SC6JHXFT.js → chunk-O23CQ5T4.js} +27 -27
  14. package/dist/cli-bundle/chunks/{chunk-SEJ53XDN.js → chunk-UIAH7UFK.js} +65 -65
  15. package/dist/cli-bundle/chunks/{chunk-2AQKVJMW.js → chunk-USTAFHIM.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-PJSQAWWQ.js → chunk-XRN3JYNN.js} +73 -73
  17. package/dist/cli-bundle/chunks/{chunk-P75SO5HO.js → chunk-YM342ELM.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-list-query-R3ELWWPY.js → register-list-query-SYNBVMNG.js} +2 -2
  19. package/dist/cli-bundle/chunks/{register-mutation-WHXJXIHJ.js → register-mutation-4GSUK23D.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-operations-7ASWBYQG.js → register-operations-7FCJUC4Z.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-setup-FDRTUG54.js → register-setup-YTWW2KL5.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/{chunk-MRH4A542.js → chunk-3CAZ7Z4R.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-5MC57KRC.js → chunk-4AORVUT4.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-FBIRNSYP.js → chunk-AKB3JN57.js} +33 -33
  25. package/dist/cli-bundle/focused-chunks/{chunk-T4H6Q44B.js → chunk-EFD4ATS7.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-NXQZMKW5.js → chunk-EVMH4SKN.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-6OXJVE74.js → chunk-IDB6E3ZV.js} +27 -27
  28. package/dist/cli-bundle/focused-chunks/{chunk-2O3QFI3G.js → chunk-IQBFYQF2.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-NY6FLQTN.js → chunk-KZULQIAG.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-KLKKCHWM.js → chunk-MOUCTR72.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-7URX7FMY.js → chunk-OMBDUJWZ.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-AZE7KUHG.js → chunk-RIJQQOEZ.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-IFBA3ZAT.js → chunk-T4PZJQG4.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-DZVOCJFY.js → chunk-UPOMLSW7.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-AVP5C674.js → chunk-XB5Q2P7Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-K3AIMRIK.js → chunk-XUCXRZZZ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-4A4DO5ZT.js → chunk-ZJ3CLTV4.js} +2 -2
  38. package/dist/cli-bundle/main.js +2 -2
  39. package/dist/cli-bundle/sdk-authoring.js +1 -1
  40. package/dist/cli-bundle/sdk-contracts.js +1 -1
  41. package/dist/cli-bundle/sdk-core.js +22 -22
  42. package/dist/cli-bundle/sdk-governance.js +1 -1
  43. package/dist/cli-bundle/sdk-graph.js +1 -1
  44. package/dist/cli-bundle/sdk-merge.js +32 -32
  45. package/dist/cli-bundle/sdk-query.js +1 -1
  46. package/dist/cli-bundle/sdk-runtime.js +1 -1
  47. package/dist/cli-bundle/sdk-testing.js +1 -1
  48. package/dist/cli-bundle/sdk.js +2 -2
  49. package/dist/core/extensions/extension-types.d.ts +13 -0
  50. package/dist/core/extensions/extension-types.js +1 -1
  51. package/dist/core/history/workspace-history.d.ts +17 -0
  52. package/dist/core/history/workspace-history.js +1 -1
  53. package/dist/sdk/extension-command-context.d.ts +1 -7
  54. package/dist/sdk/extension-command-context.js +1 -1
  55. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  56. package/dist/sdk/lifecycle/update.d.ts +2 -0
  57. package/dist/sdk/lifecycle/update.js +1 -1
  58. package/dist/sdk/merge/install.js +1 -1
  59. package/dist/sdk/public-surface.json +1 -1
  60. package/dist/sdk/runtime.js +1 -1
  61. package/dist/sdk/structured-mutations.js +1 -1
  62. package/dist/sdk/testing.js +1 -1
  63. package/docs/MERGE_SAFETY.md +11 -6
  64. package/docs/README.md +1 -0
  65. package/docs/RELEASE_RELIABILITY.md +26 -4
  66. package/docs/SDK_AUDITED_MUTATIONS.md +52 -0
  67. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  68. package/marketplace.json +2 -2
  69. package/package.json +1 -1
  70. package/packages/pm-beads/package.json +1 -1
  71. package/packages/pm-calendar/package.json +1 -1
  72. package/packages/pm-command-kit/package.json +1 -1
  73. package/packages/pm-digital-twin/package.json +1 -1
  74. package/packages/pm-governance-audit/package.json +1 -1
  75. package/packages/pm-guide-shell/package.json +1 -1
  76. package/packages/pm-kanban/package.json +1 -1
  77. package/packages/pm-lifecycle-hooks/package.json +1 -1
  78. package/packages/pm-linked-test-adapters/package.json +1 -1
  79. package/packages/pm-search-advanced/package.json +1 -1
  80. package/packages/pm-templates/package.json +1 -1
  81. package/packages/pm-todos/package.json +1 -1
  82. package/packages/pm-vcs/package.json +1 -1
  83. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  84. package/plugins/pm-claude/package.json +2 -2
  85. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  86. package/plugins/pm-codex/package.json +2 -2
  87. package/plugins/pm-codex/plugin.json +1 -1
  88. package/dist/cli-bundle/chunks/chunk-D32HVIB2.js +0 -2
@@ -1,4 +1,4 @@
1
- import{n as pu,o as jo,p as yu,q as vu,r as ya,s as zo,t as wu,u as va,v as Bo,y as Wu,z as Yu}from"./focused-chunks/chunk-K3AIMRIK.js";import{a as Zu,f as ep,h as en,m as tp,o as ur,r as Qo,s as np,t as rp,x as op}from"./focused-chunks/chunk-NY6FLQTN.js";import{$ as Un,$a as Jf,A as Er,Ab as l_,B as lf,Bb as d_,C as ki,Cb as m_,D as df,Db as u_,E as mf,Eb as p_,Fb as Cr,Ga as jf,Gb as rc,Hb as oc,Ia as Kf,Ib as xi,J as uf,Ja as Ci,Jb as ic,K as pf,Ka as uk,Kb as f_,L as ff,La as zf,Lb as sc,M as _f,Ma as Bf,Mb as Pi,N as hf,Na as nc,Nb as qn,O as gf,Ob as ac,P as yf,Pb as cc,Q as vf,Qb as __,R as wf,Rb as h_,S as bf,Sb as g_,T as kf,Tb as Kn,U as Sf,Ub as lc,V as Ef,Vb as y_,W as Af,X as Tf,Y as Cf,Ya as Vf,Yb as Ni,Z as If,Za as Wf,_ as Rf,_a as Yf,aa as Of,ab as Xf,ba as xf,bb as Qf,ca as Pf,cb as Zf,da as Ut,db as nn,dc as v_,ea as w,eb as e_,ec as w_,fa as Nf,fb as t_,fc as b_,g as tf,ga as Lf,gb as Ii,h as nf,ha as Fe,hb as n_,ia as $f,ib as r_,ja as Xa,jb as o_,jc as k_,ka as Ff,kb as i_,kc as P_,la as Qa,lb as s_,ma as Ar,mb as Ri,na as Si,nb as Gt,oa as Gn,ob as a_,pa as Mf,pb as Oi,qa as Za,ra as ge,sa as ec,sb as Tr,ta as _e,ua as Df,va as Uf,wa as Ei,xa as Gf,y as cf,ya as Ai,z as Wa,zb as c_}from"./focused-chunks/chunk-FBIRNSYP.js";import{e as du,g as mu,h as uu,k as fu,q as gu}from"./focused-chunks/chunk-IFBA3ZAT.js";import{b as Ju,c as Xo,e as Xu,f as Qu,g as Yb}from"./focused-chunks/chunk-KLKKCHWM.js";import{R as La,V as Vu,a as tm,b as nm,c as rm,d as om,f as im}from"./focused-chunks/chunk-5MC57KRC.js";import{a as of,b as sf,c as Li}from"./focused-chunks/chunk-AZE7KUHG.js";import{K as Hf,b as af}from"./focused-chunks/chunk-NXQZMKW5.js";import{Ba as fc,Da as R_,Sa as Or,Ua as O_,Va as x_,c as Ya,e as Ja,g as tc,h as Ir,i as pk,j as dc,k as mc,l as $i,m as fk,n as _k,pa as uc,s as S_,t as E_,u as A_,ua as Rr,v as T_,w as C_,wa as pc,x as I_}from"./focused-chunks/chunk-T4H6Q44B.js";import{$a as wr,A as pe,B as Ln,C as mi,D as ui,G as pi,H as fi,I as Dp,Ia as Dn,J as _i,Ja as Yp,K as hi,Ka as Ha,L as $n,La as Jp,M as za,N as gi,O as Up,Oa as Va,P as Gp,Pa as Xp,Q as yr,Xa as vi,_a as Zp,a as Np,b as ni,c as ri,cb as ef,d as oi,e as ii,i as si,j as Nt,k as Pn,kb as ht,l as ai,m as Nn,mb as Sr,n as ci,nb as tn,o as le,p as li,pb as rf,q as qa,qb as Ti,r as He,s as Ka,sa as Wp,t as Lp,u as Ce,vb as jn,w as ft,x as $p,y as di,z as Lt}from"./focused-chunks/chunk-DZVOCJFY.js";import{c as au,f as cu,g as lu,i as Go,j as Ot,k as bu,l as ku,m as Su}from"./focused-chunks/chunk-2O3QFI3G.js";import{a as sp,b as ap,c as cp}from"./focused-chunks/chunk-7URX7FMY.js";import{$ as Nm,A as ho,Aa as Zm,B as pm,Ba as eu,C as fm,Ca as To,D as _m,Da as tu,E as go,Ea as nu,F as hm,Fa as ru,G as gm,Ga as Co,H as ym,Ha as Io,I as vm,Ia as Ro,J as yo,Ja as Oo,K as vo,Ka as dr,L as wm,La as ou,M as wo,Ma as xo,Na as mr,O as bm,Oa as Po,P as cr,Pa as No,Q as km,Qa as Lo,R as Sm,Ra as $o,S as Em,Sa as iu,T as Am,Ta as It,U as Tm,Ua as Fo,V as Cm,Va as Mo,W as Im,Wa as Do,X as Rm,Xa as Uo,Y as Om,Z as xm,_ as Pm,_a as su,aa as Lm,ab as Rt,ba as $m,bb as N,ca as Fm,d as _a,da as lr,e as sm,ea as Mm,fa as Dm,ga as bo,h as uo,ha as ko,i as ha,ia as Um,j as Xt,ja as Gm,ka as jm,l as am,la as qm,ma as Km,na as zm,oa as Bm,pa as Hm,q as ga,ra as Vm,s as po,sa as Wm,t as fo,ta as Ym,u as _o,ua as Jm,v as cm,va as Xm,w as lm,wa as Qm,x as dm,xa as So,y as mm,ya as Eo,z as um,za as Ao}from"./focused-chunks/chunk-AVP5C674.js";import{$ as vp,$a as Fn,A as mk,Ab as fe,B as xn,Bb as Bp,C,Cb as yi,Db as _t,Eb as Hp,Fb as se,G as pt,Ga as Ip,Gb as Vp,Ia as ja,K as mp,Kb as Qp,L as ti,La as Rp,M as up,Ma as Op,N as pp,Na as nt,O as fp,P as _p,Q as hp,Qa as xp,Qb as br,Ra as Pp,Rb as kr,S as ee,Sa as A,Sb as wi,T as $a,Ta as $e,Tb as Dt,U as ne,Ua as Te,Va as Fp,W as Fa,Wa as Mp,X as gp,Xa as $t,Y as Be,Yb as bi,Z as et,Za as qe,_ as yp,_a as gr,a as Jb,ab as jp,b as Xb,ba as wp,bb as Mn,c as Qb,ca as bp,cb as Ba,d as Zb,da as Ma,db as qp,ga as Da,ia as kp,j as Zo,ja as Sp,jb as vr,k as lp,ka as Ep,l as dp,la as Ap,m as On,ma as Tp,n as pr,nc as qf,o as ek,p as tk,q as nk,qa as Le,qb as Ft,r as rk,ra as Pt,s as ok,sb as Mt,t as ik,ta as Ua,u as sk,ua as fr,ub as Kp,v as ak,va as _r,vb as I,w as ck,wa as Ga,wb as q,x as ei,xa as tt,xb as ie,y as lk,ya as Cp,yb as zp,z as dk,za as hr}from"./focused-chunks/chunk-6OXJVE74.js";import{b as Tt,c as so,d as ao,g as mt,i as qo,j as ut,k as xt,l as _u,n as F,o as Ko,p as Ze,r as hu}from"./focused-chunks/chunk-4A4DO5ZT.js";import{e as ip}from"./focused-chunks/chunk-HFAW3FJQ.js";import{$ as d,$a as ue,$b as Au,Ab as ar,Ac as $u,Ad as Fb,B as Ld,Bd as Mb,C as $d,Cc as Sa,D as Fd,Dc as Ea,Dd as Db,De as Bb,E as Md,Ec as Aa,Ee as Hb,F as Dd,Fb as ke,Fc as Ta,Fd as Ub,Fe as Vb,G as Ud,Ga as En,Gc as Ca,Gd as Gb,Ge as Wb,H as ia,Hb as B,Hc as Ia,Hd as xa,He as Jo,I as sa,Ia as Bd,Ic as Ra,Id as Pa,Ie as Hu,J as aa,Jb as Jt,Jc as R,Jd as Na,K as ca,Ka as ua,Kc as Cn,Kd as Uu,L as la,Lc as Qt,M as da,Mc as J,Md as Gu,Na as pa,Nc as Ho,Nd as jb,Oa as rr,Oc as In,P as io,Pa as Ee,Pb as Tn,Pd as qb,Qd as Kb,Rc as Vo,Rd as zb,Sa as x,Ta as be,Tc as Se,Td as S,U as ma,Ua as lo,Uc as Wo,Va as An,W as Gd,Wa as or,Xa as Hd,Xc as Fu,Xd as Yo,Ya as E,Yc as Zt,Z as At,Za as Vd,Zd as oe,_a as ct,_b as Eu,aa as l,ab as lt,ac as Tu,ae as Ae,bc as Cu,cb as Qe,cc as Iu,db as mo,dc as Ru,ec as wa,fc as Ou,ge as ju,hb as Wd,hc as xu,ia as jd,ib as Yd,ic as Pu,jb as Jd,ka as qd,kb as Xd,kd as Mu,lb as Qd,lc as ba,ma as co,mb as Zd,mc as Nu,nb as em,nc as ka,ne as qu,o as no,oa as Kd,od as Du,oe as Ku,p as Nd,pa as zd,pb as ir,q as ro,qb as Yt,r as oa,rb as dt,re as Rn,sa as G,ta as Wt,td as Oa,ua as Ct,uc as Lu,v as Vt,va as Z,ve as zu,w as at,wa as te,x as bn,y as kn,ya as Sn,yb as sr,z as oo,zb as fa,ze as Bu}from"./focused-chunks/chunk-MRH4A542.js";import{AsyncLocalStorage as QF}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]="1979adcd-4a7f-5dc7-b5dd-6bfc15eed1af")}catch{}})();var hk=La("list").properties.outputSession,gk={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:{...hk},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},N_={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."}},L_={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},ae={type:"string",description:"pm item id, for example pm-abc1."},yk=`Operation name (one of): ${ka.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,vk={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."}},wk={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{...L_,properties:{...L_.properties,...e},required:t}}var bk=[{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:[...ka],description:yk},id:ae,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."},...gk},["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"},...wk},["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"},...vk})},{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:ae,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:ae,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:ae,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:ae,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:ae,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:ae,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:ae,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:ae,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:ae,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:ae,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:ae,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:ae,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:ae,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:ae,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:ae,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:[...Ou]},id:ae,target:ae,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:ae,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({...N_,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",...Tn],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:[...oa]},description:`Lifecycle roles for add-status: ${oa.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:N_}},["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."}})}],kk={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"},Sk=bk.map(e=>{let t=kk[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:La(t,{properties:n,required:r})}});function $_(){return Sk.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]="845638dd-45b8-5057-bed2-2f687591eeaa")}catch{}})();var F_=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"]]]),Ek=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],H_=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Mi=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"]),V_=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"]]),W_=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"]]),Y_=new Map([...W_.entries()].flatMap(([e,t])=>gt(t).map(n=>[n,e]))),J_=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],gc=new Map(J_.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),Ak=10,Tk=20,M_=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."]]),X_=[["init",bm],["install",Sm],["uninstall",Em],["explore",Am],["manage",xm],["describe",Tm],["reload",Pm],["doctor",Nm],["catalog",Lm],["adopt",$m],["adopt-all",Cm],["activate",Im],["deactivate",Rm],["migrate",Om]],Ck=[...X_.map(([e,t])=>e==="init"?[e,km]:[e,t]),["upgrade",lr]],Ik=[...X_.map(([e,t])=>[`extension ${e}`,t]),...Ck.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",vo],["config",wm],["extension",wo],["package",cr],["packages",cr],["install",Fm],["create",To],["item mutate",tu],["item complete",nu],["item reopen",ru],["copy",Co],["focus",Io],["update",Ro],["update-many",Oo],["upgrade",lr],["calendar",dr],["cal",dr],["context",mr],["ctx",mr],["get",Po],["search",Mo],["eval",iu],["events",xo],["workspace",It],["workspace position",[]],["workspace snapshot",It],["workspace snapshot create",It],["workspace snapshot list",It],["workspace snapshot inspect",It],["workspace snapshot restore",It],["workspace snapshot delete",It],["next",Fo],["aggregate",_o],["deps",Lo],["graph",$o],["guide",No],["reindex",Mm],["history",ho],["history-compact",hm],["history-attest",gm],["history-redact",fm],["history-repair",_m],["history-author-acknowledge",go],["merge",pm],["schema",ym],["profile",vm],["plan",yo],["restore",Gm],["delete",jm],["close",Dm],["close-many",bo],["append",ko],["claim",Um],["release",qm],["start-task",Km],["pause-task",zm],["close-task",Bm],["comments",cm],["notes",lm],["learnings",dm],["files",mm],["docs",um],["test",Wm],["test-runs-worker",[]],["test-all",Ym],["telemetry",Jm],["test-runs",Xm],["gc",Qm],["stats",So],["ops",[]],["duplicates",Eo],["validate",Zm],["health",Ao],["assurance",eu],...su,["contracts",Do],["completion",Uo],["activity",ou],...[...H_].map(e=>[e,fo])],xr=new Map(Ik);for(let{alias:e,canonical:t}of ke){let n=xr.get(e);n!==void 0&&xr.set(t,n)}function Rk(e){let t=Y_.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function D_(e){let t=ke.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:wa.includes(e)?ye(e):e.startsWith("extension-")?ye(`extension ${e.slice(10)}`):e.startsWith("package-")?ye(`package ${e.slice(8)}`):e.startsWith("item-")?ye(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ye(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ye(`templates ${e.slice(10)}`):Mi.has(e)?W_.get(e)??ye(e):null}function Ok(e,t){let n=B(t);return n!==t||ke.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:gt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function gt(e){return e.split("|").map(t=>ye(t)).filter(t=>t.length>0)}function xk(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 s=i.split(" ").filter(a=>a.length>0);if(s.length!==0)for(let a=s.length;a>0;a-=1){let c=s.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function Fi(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Pr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function Pk(e,t){if(!t)return{...e};let r=Pr(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;return typeof s!="object"||s===null?!1:s.const===t});return{...e,oneOf:r}}function _c(e,t){let r=Pr(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;if(typeof s!="object"||s===null)return!1;let a=s.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function ye(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Q_(e){return e.replace(/\s+/g,"-")}function rt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function U_(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=rt(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function hc(e,t,n){n&&(e[t]=!0)}function G_(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 Nk(e){let t=G_(e.long,"long"),n=G_(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),hc(o,"required",e.required===!0),hc(o,"repeatable",e.repeatable===!0),hc(o,"list",e.list===!0);let i=rt(e.description);i&&(o.description=i);let s=rt(e.value_name);s&&(o.value_name=s);let a=[rt(e.value_type),rt(e.type),s?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function Z_(e){let t=new Map;for(let r of e){let o=ye(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},s=`${r.layer}:${r.name}`;i.sourceDedupe.has(s)||(i.sourceDedupe.add(s),i.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=Nk(a);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,s)=>{let a=i.layer.localeCompare(s.layer);return a!==0?a:(i.name??"").localeCompare(s.name??"")})});return n}function Lk(e){let t=Z_(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let s=ye(i.command);if(s.length===0)continue;let a=rt(i.action)??Q_(s),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let u=rt(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:rt(m.description)}:null}).filter(m=>m!==null):[];n.set(s,{...i.tier===void 0?{}:{tier:i.tier},command:s,action:a,source:{layer:i.layer,name:i.name},description:rt(i.description),intent:rt(i.intent),arguments:c,flags:t.get(s)?.flags??[],examples:U_(i.examples),failure_hints:U_(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(ye(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((s,a)=>s.localeCompare(a))){let s=n.get(i);o.push($k(i,s,t.get(i)?.flags??[]))}return o}function $k(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Q_(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Fk(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,i)=>i.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function Mk(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 Dk(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 Uk(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]=Mk(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=Fk(o);!i||n[i]!==void 0||(n[i]=Dk(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 Gk(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 jk(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,s)=>i.localeCompare(s)).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 s=`${i.flag}|${i.short??""}`;if(!o.has(s))o.add(s),r.flags.push(i);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===s);a&&Gk(a,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 qk(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 G(ue(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await sr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),s=await ar({...i,loaded:i.loaded});return{handlers:new Set(s.commands.handlers.map(c=>ye(c.command))),disabledReason:null,commandDefinitions:s.registrations.commands,flagRegistrations:s.registrations.flags,registrations:s.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 Kk(e,t={}){let n=new Map;for(let r of ba){let o=Mi.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=D_(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Mi)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:D_(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ke.find(o=>o.alias===r.command)?.canonical??ye(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function zk(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(s=>t.handlers.has(s)||t.handlers.has(B(s))),o=n.map(s=>V_.get(B(s))).find(s=>typeof s=="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 eh(e){return xr.get(e)??po}function Bk(e){return rn.has(B(e))?!1:xr.has(e)}function Hk(e){return H_.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 Vk(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Wk(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(a=>Vk(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>j_(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=i?{flag:o,short:i}:{flag:o},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of s){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,ga(o.flags));return n}function q_(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 ga(n)}function Yk(e,t,n,r,o){let i=new Map(t);for(let{alias:s,canonical:a}of ke){let c=t.get(a)??t.get(s);c&&(i.set(s,c),i.set(a,c))}return e.map(s=>{let a=Bk(s),c=a?eh(s):[],m=n.get(Hk(s))??[],u=i.get(s),p=q_(c,m),f=q_(p,u?.flags??[]),_=c.length>0&&(u?.flags.length??0)>0?"mixed":a?"core":"extension";return{command:s,flags:f,...r?{canonical_command:nh(s),visibility:th(s,o),positionals:sm(s)?.slots??[],flag_invocations:ur(s,f)}:{},provider:_,extension_sources:u?.sources}}).sort((s,a)=>s.command.localeCompare(a.command))}function Jk(e,t=Jt){let n=new Set(e),r=new Map;for(let o of J_){let i=o.aliases.filter(s=>n.has(s));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 Xk(){return{create_string_options:Ju,create_repeatable_options:Xo,update_string_options:Xu,update_repeatable_options:Qu,list_string_options:tm,search_string_options:nm,calendar_string_options:rm,context_string_options:om,activity_string_options:im}}function K_(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=An(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),i=[...new Set(o.map(a=>Ee("create",a)))].sort((a,c)=>a.localeCompare(c)),s=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:s,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function Qk(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=K_(o,"strict"),n[r]=K_(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Zk(e,t){let n=Pr(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let s=i.properties;if(typeof s!="object"||s===null)return i;let a=s.action;return typeof a!="object"||a===null||a.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function eS(e){let t=Fi(e.action)!==void 0||Fi(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,s=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=Fi(e.action),u=Fi(e.command),p=!r&&!c&&!o&&!i&&!s&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:s,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function tS(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function nS(e,t=A){try{return await t(e)}catch{return structuredClone(At)}}async function rS(e,t,n){let r=await nS(t),o=await qk(e),i=x(r,o.registrations??R()),s=Ze(r.schema),a=Lk(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:F(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:Wk(s),createRequiredOptionContracts:Qk(i),extensionContracts:a,mergedExtensionContracts:jk(a.filter(c=>Di(n,c.command,a))),extensionFlagMap:Z_(o.flagRegistrations)}}function z_(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Mi.has(e.selectedAction)||e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand)))}function oS(e,t){let n=Kk(t,{includePackageOwnedActions:z_(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Nu);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??Qo(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:Rk(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function iS(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 sS(e,t){return[...new Set([...wa.filter(n=>!rn.has(B(n))),...[...xr.keys()].filter(n=>!rn.has(B(n))),...e.flatMap(n=>n.command_path?gt(n.command_path).filter(r=>n.provider==="extension"||!rn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=ke.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>ye(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function aS(e,t){let n=t.slice(0,Ak),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,Tk),s=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=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:s,nextSteps:[`Retry with a child command, for example: ${s[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --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 cS(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 lS(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 dS(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(r.length>0)throw aS(e.selectedCommand,r);let o=V_.get(B(e.selectedCommand));throw o?cS(e.selectedCommand,o):lS(e.selectedCommand)}function mS(e,t){let n=oS(e,t.mergedExtensionContracts);iS(e,n);let r=sS(n,t.mergedExtensionContracts);dS(e,r);let o=e.selectedCommand?Y_.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:Ok(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 s=e.selectedAction?i.filter(m=>m.action===e.selectedAction):i,a=[...new Map(s.map(m=>zk(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:s,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function uS(e){return new Set(Pr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function pS(e){let t=Vu,n=Pr(t),r=uS(t),o=e.filter(i=>!r.has(i.action)).map(i=>Uk(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function B_(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?Pk(n,e.selectedAction):e.selectedCommand?_c(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):_c(n,r);return e.runtimeOnly&&!e.selectedAction?_c(o,new Set(t.actions)):o}function fS(e,t,n){let r=pS(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?Zk(B_(e,n,r),t.createRequiredOptionContracts):B_(e,n,r);return{mergedSchema:r,filteredSchema:i}}function _S(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?xk(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function th(e,t){return t.find(n=>B(n.command)===B(e))?.tier??Qo(e)}function Di(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||th(t,n)!=="internal"}function hS(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 gc.keys())r.add(o);return t.filter(o=>!r.has(o)&&Di(e,o,n))}function nh(e){let t=ke.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":gc.get(n)??n}var gS=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"]]),yS=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function vS(e,t){let n=M_.get(B(e))??(e.includes(" ")?void 0:M_.get(nh(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>gt(m.command).some(u=>B(u)===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),s=o.slice(0,-1).join(" "),a=gS.get(i),c=yS.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function wS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ye))].filter(i=>i.length>0).sort((i,s)=>i.localeCompare(s)).map(i=>{let s=Oa(i,{generateFallback:!0}),a=i.split(" ")[0],c=gc.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...eh(i).map(f=>f.flag),...t.filter(f=>gt(f.command).some(_=>B(_)===B(i))).flatMap(f=>f.flags.map(_=>_.flag))]),u=(F_.get(B(i))??F_.get(c)??Ek).filter(f=>m.has(f)),p=vS(i,t);return{command:i,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:s.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...s.default_max_estimated_tokens_by_format}}:{}}})}function bS(e){return e.map(t=>({budget:Oa(t,{generateFallback:!0}),envelope:op(t)}))}function kS(e){let t=new Map;for(let n of e){let r=ep(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(","),s=t.get(i)??{commands:[],exit_codes:o};s.commands.push(n),t.set(i,s)}return[...t.values()]}function SS(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=>Di(e,r.command,t.extensionContracts))}function ES(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 AS(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=ip);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(s=>`--${s.cli_flag}`))].sort((s,a)=>s.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Eu],services:[...Au],policy_modes:[...Tu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Ru],trust_modes:[...Cu],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Iu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Ld],create_modes:[...$d],close_validation_modes:[...Fd],workflow_enforcement_modes:[...Md]},e.relationship_kind_contracts=[...jd,...(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 TS(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 CS(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=Yk(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(cp).filter(([s])=>i.has(s)).map(([s,a])=>({command:s,default:a,brief_fields:[...ap],compact_fields:[...sp]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:s})=>({canonical:i,aliases:s})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function IS(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Xk();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function RS(e,t,n,r){e.command_summaries=wS(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Mu],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(ye))].filter(o=>Pa(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...Uu(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(ha.map(({slots:o})=>am(o))).size,positional_action_count:_a.length,positional_action_parents:[...new Set(_a.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:ha}:{}}}async function yc(e,t){let n=eS(e);tS(n);let r=E(process.cwd(),t.path),o=await rS(t,r,n),i=mS(n,o),s=fS(n,o,i),a=_S(n,i),c=hS(n,a,o.extensionContracts),m=ES(n,s,i,c),u=SS(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&RS(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=Jk(i.commandCatalog.filter(_=>Di(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||AS(m,o,n),TS(m,n,s,u),CS(m,n,o,c,f),IS(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...nf],gate_triggers:[...tf]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=uo.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=$_(),m.context_intents=qu(),m.read_output_dimensions=xa,m.error_codes=tp,m.command_output_contracts=bS(c),m.diagnostic_output_contracts=Du,m.command_exit_contracts={vocabulary:Zu,command_sets:kS(c)}),m}import{readFile as OS}from"node:fs/promises";import xS 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]="c64f304d-9081-5bad-8187-7bf6b65e4a07")}catch{}})();var vc="context-intents.json";function Ui(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function PS(e,t,n){if(!Ui(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 rh(e,t){let n=Array.isArray(e)?e:Ui(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)=>PS(r,t,o))}async function NS(e){let t=xS.join(e,vc),n;try{n=await OS(t,"utf8")}catch(o){if(Wt(o))return[];throw await Kp(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${vc}: ${i}`,{cause:o})}return rh(r,vc)}function LS(e){if(!Ui(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Ui(n)?n.contextIntents??n.context_intents:void 0}function $S(e){return e.flatMap(t=>{let n=LS(t.module);return n===void 0?[]:rh(n,`package ${t.name}`)})}async function FS(e){let t=await NS(e.pmRoot),n=$S(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function wc(e,t){let n=await FS(e);return await Ku(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]="c2766f4e-6354-55bb-9e40-676273ee901f")}catch{}})();async function oh(e,t,n=ju){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()}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9133d39d-b2fb-5f99-8fd3-87a7d2f8df6d")}catch{}})();var bc="PmCliError";function MS(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function ih(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,MS(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Gi(e){if(!(e instanceof Error)||e.name!==bc)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3113ad4b-282a-50af-a836-8e9abfde7d7e")}catch{}})();function kc(e){let t=qd();for(let n of e)t.register(n);return t}function sh(e,t){return{client:t,isItemNotFoundError:n=>Gi(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>rf(n,r,{pmRoot:e}),openRelationshipEventStore:n=>sf.open({pmRoot:e,nodes:n.nodes,registry:kc(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new zd(n.nodes,n.edges,kc(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>af(n,r,o),validateRelationshipEvents:n=>{let r=new of(n.nodes,{registry:kc(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>cf({...n,pmRoot:e})}}import DS from"node:fs/promises";import X from"node:path";import US from"node:readline/promises";import{stdin as GS,stdout as Me}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="231597cc-2166-5029-9b3a-476587a33941")}catch{}})();var Ec=Symbol.for("pm.sdk.init-invocation-cwd");var jS=()=>US.createInterface({input:GS,output:Me});function qS(){return structuredClone(At)}var KS=["minimal","default","strict"];function ch(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: ${KS.join(", ")}`,d.USAGE)}function zS(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return mu(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${du.join(", ")}`,d.USAGE)}}}function BS(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 Sc(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 HS(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||Sc(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),u=X.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&Sc(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),s=X.join(X.resolve(e),".agents","pm"),a=X.dirname(X.dirname(i)),c=X.resolve(i)===s?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:a,discovery:c,requested_cwd:X.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:s}:{}}:{mode:"tracker-path",tracker_root:i}}}function VS(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(Sc(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&&$t(e)!==$t(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 ${$t(e)}`,`pm init --id-prefix ${$t(t)}`]});return t}function WS(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: ${Of.join(", ")}`,d.USAGE)}function YS(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function lh(e,t){let n=Gd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function JS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function XS(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(JS).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function QS(e,t,n){let r=qo(t.schema),o=ut(e,r.files.types,mt.types),s=cu(await Z(o)),a=[],c=[];for(let m of uu(n)){let u=lu(s,m);s=u.file,(u.replaced?c:a).push(u.definition.name)}return await nt({pmRoot:e,filePath:o,raw:Go(s),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:c,file:o}}async function ZS(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",X.join(".agents","pm")];for(let n of t)if(await G(X.join(e,n)))return!0;return!1}async function eE(e,t,n){if(!t||n||await G(X.join(e,"settings.json"))||!await ZS(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 dh(e,t){let n=[],r=[];for(let o of t){let i=o?X.join(e,o):e,s=await G(i);await DS.mkdir(i,{recursive:!0}),s?r.push(`already_exists:${i}`):n.push(i),r.push(...await J({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function tE(e,t){let n=jS();try{Me.write(`pm init setup wizard (agent-optimized)
1
+ import{n as _u,o as jo,p as wu,q as bu,r as wa,s as zo,t as ku,u as ba,v as Bo,y as Ju,z as Xu}from"./focused-chunks/chunk-XUCXRZZZ.js";import{a as tp,f as np,h as en,m as rp,o as ur,r as Qo,s as op,t as ip,x as sp}from"./focused-chunks/chunk-KZULQIAG.js";import{$ as Un,$a as Zf,A as Er,Ab as u_,B as uf,Bb as p_,C as Si,Cb as f_,D as pf,Db as __,E as ff,Eb as h_,Fb as Cr,Ga as zf,Gb as ic,Hb as sc,Ia as Hf,Ib as Ni,J as _f,Ja as Ri,Jb as ac,K as hf,Ka as _k,Kb as g_,L as gf,La as Vf,Lb as cc,M as yf,Ma as Wf,Mb as Li,N as vf,Na as oc,Nb as qn,O as wf,Ob as lc,P as bf,Pb as dc,Q as kf,Qb as y_,R as Sf,Rb as v_,S as Ef,Sb as w_,T as Af,Tb as Kn,U as Tf,Ub as mc,V as Cf,Vb as b_,W as If,X as Rf,Y as Of,Ya as Jf,Yb as $i,Z as xf,Za as Xf,_ as Pf,_a as Qf,aa as Nf,ab as e_,ba as Lf,bb as t_,ca as $f,cb as n_,da as Ut,db as nn,dc as k_,ea as w,eb as r_,ec as S_,fa as Ff,fb as o_,fc as E_,g as of,ga as Mf,gb as Oi,h as sf,ha as Fe,hb as i_,ia as Df,ib as s_,ja as ec,jb as a_,jc as A_,ka as Uf,kb as c_,kc as $_,la as tc,lb as l_,ma as Ar,mb as xi,na as Ei,nb as Gt,oa as Gn,ob as d_,pa as Gf,pb as Pi,qa as Ai,ra as ge,sa as nc,sb as Tr,ta as _e,ua as jf,va as qf,wa as Ti,xa as Kf,y as mf,ya as Ci,z as Xa,zb as m_}from"./focused-chunks/chunk-AKB3JN57.js";import{e as uu,g as pu,h as fu,k as hu,q as vu}from"./focused-chunks/chunk-T4PZJQG4.js";import{b as Qu,c as Xo,e as Zu,f as ep,g as Qb}from"./focused-chunks/chunk-MOUCTR72.js";import{R as Fa,V as Yu,a as rm,b as om,c as im,d as sm,f as am}from"./focused-chunks/chunk-4AORVUT4.js";import{a as cf,b as lf,c as Fi}from"./focused-chunks/chunk-RIJQQOEZ.js";import{K as Yf,b as df}from"./focused-chunks/chunk-EVMH4SKN.js";import{Ba as hc,Da as P_,Sa as Or,Ua as N_,Va as L_,c as Qa,e as Za,g as rc,h as Ir,i as hk,j as uc,k as pc,l as Mi,m as gk,n as yk,pa as fc,s as T_,t as C_,u as I_,ua as Rr,v as R_,w as O_,wa as _c,x as x_}from"./focused-chunks/chunk-EFD4ATS7.js";import{$a as wr,A as pe,B as Ln,C as ui,D as pi,G as fi,H as _i,I as jp,Ia as Dn,J as hi,Ja as Qp,K as gi,Ka as Ya,L as $n,La as Zp,M as Va,N as yi,O as qp,Oa as Ja,P as Kp,Pa as ef,Q as yr,Xa as wi,_a as nf,a as Fp,b as ri,c as oi,cb as rf,d as ii,e as si,i as ai,j as Nt,k as Pn,kb as ht,l as ci,m as Nn,mb as Sr,n as li,nb as tn,o as de,p as di,pb as af,q as Ba,qb as Ii,r as Ve,s as Ha,sa as Xp,t as Mp,u as Ce,vb as jn,w as ft,x as Dp,y as mi,z as Lt}from"./focused-chunks/chunk-UPOMLSW7.js";import{c as lu,f as du,g as mu,i as Go,j as Ot,k as Su,l as Eu,m as Au}from"./focused-chunks/chunk-IQBFYQF2.js";import{a as cp,b as lp,c as dp}from"./focused-chunks/chunk-OMBDUJWZ.js";import{$ as $m,A as ho,Aa as tu,B as _m,Ba as nu,C as hm,Ca as To,D as gm,Da as ru,E as go,Ea as ou,F as ym,Fa as iu,G as vm,Ga as Co,H as wm,Ha as Io,I as bm,Ia as Ro,J as yo,Ja as Oo,K as vo,Ka as dr,L as km,La as su,M as wo,Ma as xo,Na as mr,O as Sm,Oa as Po,P as cr,Pa as No,Q as Em,Qa as Lo,R as Am,Ra as $o,S as Tm,Sa as au,T as Cm,Ta as It,U as Im,Ua as Fo,V as Rm,Va as Mo,W as Om,Wa as Do,X as xm,Xa as Uo,Y as Pm,Z as Nm,_ as Lm,_a as cu,aa as Fm,ab as Rt,ba as Mm,bb as N,ca as Dm,d as ga,da as lr,e as cm,ea as Um,fa as Gm,ga as bo,h as uo,ha as ko,i as ya,ia as jm,j as Xt,ja as qm,ka as Km,l as lm,la as zm,ma as Bm,na as Hm,oa as Vm,pa as Wm,q as va,ra as Ym,s as po,sa as Jm,t as fo,ta as Xm,u as _o,ua as Qm,v as dm,va as Zm,w as mm,wa as eu,x as um,xa as So,y as pm,ya as Eo,z as fm,za as Ao}from"./focused-chunks/chunk-XB5Q2P7Z.js";import{$ as wp,$a as Ke,A as pk,Aa as hr,Ab as Vp,B as fk,C as xn,Cb as fe,D as C,Db as Wp,Eb as vi,Fb as _t,Gb as Yp,H as pt,Ha as Op,Hb as ae,Ib as Jp,Ja as za,L as pp,M as ti,Ma as xp,Mb as tf,N as fp,Na as ni,O as _p,Oa as rt,P as hp,Q as gp,Qa as Pp,R as yp,Ra as Np,Sa as Lp,Sb as br,T as ee,Ta as $p,Tb as kr,U as Da,Ua as A,Ub as bi,V as re,Va as $e,Vb as Dt,Wa as Te,X as Ua,Xa as Up,Y as vp,Ya as Gp,Z as He,Za as $t,_ as tt,_b as ki,a as Ma,aa as bp,ab as gr,b as Zb,bb as Fn,c as ek,ca as kp,cb as zp,d as tk,da as Sp,db as Mn,e as nk,ea as Ga,eb as Wa,fb as Bp,ha as ja,ja as Ep,k as Zo,ka as Ap,l as mp,la as Tp,lb as vr,m as up,ma as Cp,n as On,na as Ip,o as pr,p as rk,pc as Bf,q as ok,r as ik,ra as Le,s as sk,sa as Pt,sb as Ft,t as ak,u as ck,ua as qa,ub as Mt,v as lk,va as fr,w as dk,wa as _r,wb as Hp,x as mk,xa as Ka,xb as I,y as ei,ya as nt,yb as q,z as uk,za as Rp,zb as se}from"./focused-chunks/chunk-IDB6E3ZV.js";import{b as Tt,c as so,d as ao,g as mt,i as qo,j as ut,k as xt,l as gu,n as F,o as Ko,p as et,r as yu}from"./focused-chunks/chunk-ZJ3CLTV4.js";import{e as ap}from"./focused-chunks/chunk-HFAW3FJQ.js";import{$ as d,$a as ne,$b as Cu,Ab as ar,Ac as Mu,Ad as Ub,B as Fd,Bd as Gb,C as Md,Cc as Aa,D as Dd,Dc as Ta,Dd as jb,De as Wb,E as Ud,Ec as Ca,Ee as Yb,F as Gd,Fb as ke,Fc as Ia,Fd as qb,Fe as Jb,G as jd,Ga as En,Gc as Ra,Gd as Kb,Ge as Xb,H as aa,Hb as B,Hc as Oa,Hd as Na,He as Jo,I as ca,Ia as Vd,Ic as xa,Id as La,Ie as Wu,J as la,Jb as Jt,Jc as R,Jd as $a,K as da,Ka as fa,Kc as Cn,Kd as ju,L as ma,Lc as Qt,M as ua,Mc as Y,Md as qu,Na as _a,Nc as Ho,Nd as zb,Oa as rr,Oc as In,P as io,Pa as Ee,Pb as Tn,Pd as Bb,Qd as Hb,Rc as Vo,Rd as Vb,Sa as x,Ta as be,Tc as Se,Td as S,U as pa,Ua as lo,Uc as Wo,Va as An,W as qd,Wa as or,Xa as Wd,Xc as Du,Xd as Yo,Ya as E,Yc as Zt,Z as At,Za as Yd,Zd as ie,_a as lt,_b as Tu,aa as l,ab as dt,ac as Iu,ae as Ae,bc as Ru,cb as Ze,cc as Ou,db as mo,dc as xu,ec as ka,fc as Pu,ge as Ku,hb as Jd,hc as Nu,ia as Kd,ib as Xd,ic as Lu,jb as Qd,ka as zd,kb as Zd,kd as Uu,lb as em,lc as Sa,ma as co,mb as tm,mc as $u,nb as nm,nc as Ea,ne as zu,o as no,oa as Bd,od as Gu,oe as Bu,p as $d,pa as Hd,pb as ir,q as ro,qb as Yt,r as sa,rb as qe,re as Rn,sa as G,ta as Wt,td as Pa,ua as Ct,uc as Fu,v as Vt,va as Z,ve as Hu,w as ct,wa as te,x as bn,y as kn,ya as Sn,yb as sr,z as oo,zb as ha,ze as Vu}from"./focused-chunks/chunk-3CAZ7Z4R.js";import{AsyncLocalStorage as rM}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]="1979adcd-4a7f-5dc7-b5dd-6bfc15eed1af")}catch{}})();var vk=Fa("list").properties.outputSession,wk={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:{...vk},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},F_={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."}},M_={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."},bk=`Operation name (one of): ${Ea.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,kk={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."}},Sk={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{...M_,properties:{...M_.properties,...e},required:t}}var Ek=[{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:[...Ea],description:bk},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."},...wk},["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"},...Sk},["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"},...kk})},{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:[...Pu]},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({...F_,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",...Tn],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:[...sa]},description:`Lifecycle roles for add-status: ${sa.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:F_}},["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."}})}],Ak={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"},Tk=Ek.map(e=>{let t=Ak[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Fa(t,{properties:n,required:r})}});function D_(){return Tk.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]="845638dd-45b8-5057-bed2-2f687591eeaa")}catch{}})();var U_=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"]]]),Ck=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Y_=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Ui=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"]),J_=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"]]),X_=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"]]),Q_=new Map([...X_.entries()].flatMap(([e,t])=>gt(t).map(n=>[n,e]))),Z_=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],vc=new Map(Z_.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),Ik=10,Rk=20,G_=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."]]),eh=[["init",Sm],["install",Am],["uninstall",Tm],["explore",Cm],["manage",Nm],["describe",Im],["reload",Lm],["doctor",$m],["catalog",Fm],["adopt",Mm],["adopt-all",Rm],["activate",Om],["deactivate",xm],["migrate",Pm]],Ok=[...eh.map(([e,t])=>e==="init"?[e,Em]:[e,t]),["upgrade",lr]],xk=[...eh.map(([e,t])=>[`extension ${e}`,t]),...Ok.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",vo],["config",km],["extension",wo],["package",cr],["packages",cr],["install",Dm],["create",To],["item mutate",ru],["item complete",ou],["item reopen",iu],["copy",Co],["focus",Io],["update",Ro],["update-many",Oo],["upgrade",lr],["calendar",dr],["cal",dr],["context",mr],["ctx",mr],["get",Po],["search",Mo],["eval",au],["events",xo],["workspace",It],["workspace position",[]],["workspace snapshot",It],["workspace snapshot create",It],["workspace snapshot list",It],["workspace snapshot inspect",It],["workspace snapshot restore",It],["workspace snapshot delete",It],["next",Fo],["aggregate",_o],["deps",Lo],["graph",$o],["guide",No],["reindex",Um],["history",ho],["history-compact",ym],["history-attest",vm],["history-redact",hm],["history-repair",gm],["history-author-acknowledge",go],["merge",_m],["schema",wm],["profile",bm],["plan",yo],["restore",qm],["delete",Km],["close",Gm],["close-many",bo],["append",ko],["claim",jm],["release",zm],["start-task",Bm],["pause-task",Hm],["close-task",Vm],["comments",dm],["notes",mm],["learnings",um],["files",pm],["docs",fm],["test",Jm],["test-runs-worker",[]],["test-all",Xm],["telemetry",Qm],["test-runs",Zm],["gc",eu],["stats",So],["ops",[]],["duplicates",Eo],["validate",tu],["health",Ao],["assurance",nu],...cu,["contracts",Do],["completion",Uo],["activity",su],...[...Y_].map(e=>[e,fo])],xr=new Map(xk);for(let{alias:e,canonical:t}of ke){let n=xr.get(e);n!==void 0&&xr.set(t,n)}function Pk(e){let t=Q_.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function j_(e){let t=ke.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:ka.includes(e)?ye(e):e.startsWith("extension-")?ye(`extension ${e.slice(10)}`):e.startsWith("package-")?ye(`package ${e.slice(8)}`):e.startsWith("item-")?ye(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ye(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ye(`templates ${e.slice(10)}`):Ui.has(e)?X_.get(e)??ye(e):null}function Nk(e,t){let n=B(t);return n!==t||ke.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:gt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function gt(e){return e.split("|").map(t=>ye(t)).filter(t=>t.length>0)}function Lk(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 s=i.split(" ").filter(a=>a.length>0);if(s.length!==0)for(let a=s.length;a>0;a-=1){let c=s.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function Di(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Pr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function $k(e,t){if(!t)return{...e};let r=Pr(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;return typeof s!="object"||s===null?!1:s.const===t});return{...e,oneOf:r}}function gc(e,t){let r=Pr(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;if(typeof s!="object"||s===null)return!1;let a=s.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function ye(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function th(e){return e.replace(/\s+/g,"-")}function ot(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function q_(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=ot(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function yc(e,t,n){n&&(e[t]=!0)}function K_(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 Fk(e){let t=K_(e.long,"long"),n=K_(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),yc(o,"required",e.required===!0),yc(o,"repeatable",e.repeatable===!0),yc(o,"list",e.list===!0);let i=ot(e.description);i&&(o.description=i);let s=ot(e.value_name);s&&(o.value_name=s);let a=[ot(e.value_type),ot(e.type),s?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function nh(e){let t=new Map;for(let r of e){let o=ye(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},s=`${r.layer}:${r.name}`;i.sourceDedupe.has(s)||(i.sourceDedupe.add(s),i.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=Fk(a);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,s)=>{let a=i.layer.localeCompare(s.layer);return a!==0?a:(i.name??"").localeCompare(s.name??"")})});return n}function Mk(e){let t=nh(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let s=ye(i.command);if(s.length===0)continue;let a=ot(i.action)??th(s),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let u=ot(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:ot(m.description)}:null}).filter(m=>m!==null):[];n.set(s,{...i.tier===void 0?{}:{tier:i.tier},command:s,action:a,source:{layer:i.layer,name:i.name},description:ot(i.description),intent:ot(i.intent),arguments:c,flags:t.get(s)?.flags??[],examples:q_(i.examples),failure_hints:q_(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(ye(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((s,a)=>s.localeCompare(a))){let s=n.get(i);o.push(Dk(i,s,t.get(i)?.flags??[]))}return o}function Dk(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:th(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Uk(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,i)=>i.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function Gk(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function jk(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function qk(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]=Gk(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=Uk(o);!i||n[i]!==void 0||(n[i]=jk(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 Kk(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function zk(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((i,s)=>i.localeCompare(s)).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 s=`${i.flag}|${i.short??""}`;if(!o.has(s))o.add(s),r.flags.push(i);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===s);a&&Kk(a,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 Bk(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 G(ne(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await sr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),s=await ar({...i,loaded:i.loaded});return{handlers:new Set(s.commands.handlers.map(c=>ye(c.command))),disabledReason:null,commandDefinitions:s.registrations.commands,flagRegistrations:s.registrations.flags,registrations:s.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 Hk(e,t={}){let n=new Map;for(let r of Sa){let o=Ui.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=j_(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Ui)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:j_(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ke.find(o=>o.alias===r.command)?.canonical??ye(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function Vk(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(s=>t.handlers.has(s)||t.handlers.has(B(s))),o=n.map(s=>J_.get(B(s))).find(s=>typeof s=="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 rh(e){return xr.get(e)??po}function Wk(e){return rn.has(B(e))?!1:xr.has(e)}function Yk(e){return Y_.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function z_(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Jk(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Xk(e){let t=new Map;for(let r of e.definitions){let o=z_(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(a=>Jk(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>z_(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=i?{flag:o,short:i}:{flag:o},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of s){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,va(o.flags));return n}function B_(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 va(n)}function Qk(e,t,n,r,o){let i=new Map(t);for(let{alias:s,canonical:a}of ke){let c=t.get(a)??t.get(s);c&&(i.set(s,c),i.set(a,c))}return e.map(s=>{let a=Wk(s),c=a?rh(s):[],m=n.get(Yk(s))??[],u=i.get(s),p=B_(c,m),f=B_(p,u?.flags??[]),_=c.length>0&&(u?.flags.length??0)>0?"mixed":a?"core":"extension";return{command:s,flags:f,...r?{canonical_command:ih(s),visibility:oh(s,o),positionals:cm(s)?.slots??[],flag_invocations:ur(s,f)}:{},provider:_,extension_sources:u?.sources}}).sort((s,a)=>s.command.localeCompare(a.command))}function Zk(e,t=Jt){let n=new Set(e),r=new Map;for(let o of Z_){let i=o.aliases.filter(s=>n.has(s));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 eS(){return{create_string_options:Qu,create_repeatable_options:Xo,update_string_options:Zu,update_repeatable_options:ep,list_string_options:rm,search_string_options:om,calendar_string_options:im,context_string_options:sm,activity_string_options:am}}function H_(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=An(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),i=[...new Set(o.map(a=>Ee("create",a)))].sort((a,c)=>a.localeCompare(c)),s=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:s,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function tS(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=H_(o,"strict"),n[r]=H_(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function nS(e,t){let n=Pr(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let s=i.properties;if(typeof s!="object"||s===null)return i;let a=s.action;return typeof a!="object"||a===null||a.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function rS(e){let t=Di(e.action)!==void 0||Di(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,s=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=Di(e.action),u=Di(e.command),p=!r&&!c&&!o&&!i&&!s&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:s,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function oS(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function iS(e,t=A){try{return await t(e)}catch{return structuredClone(At)}}async function sS(e,t,n){let r=await iS(t),o=await Bk(e),i=x(r,o.registrations??R()),s=et(r.schema),a=Mk(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:F(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:Xk(s),createRequiredOptionContracts:tS(i),extensionContracts:a,mergedExtensionContracts:zk(a.filter(c=>Gi(n,c.command,a))),extensionFlagMap:nh(o.flagRegistrations)}}function V_(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ui.has(e.selectedAction)||e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand)))}function aS(e,t){let n=Hk(t,{includePackageOwnedActions:V_(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set($u);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??Qo(o.action))!=="internal"))}return V_(e)&&e.selectedCommand!==void 0&&rn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:Pk(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function cS(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 lS(e,t){return[...new Set([...ka.filter(n=>!rn.has(B(n))),...[...xr.keys()].filter(n=>!rn.has(B(n))),...e.flatMap(n=>n.command_path?gt(n.command_path).filter(r=>n.provider==="extension"||!rn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=ke.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>ye(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function dS(e,t){let n=t.slice(0,Ik),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,Rk),s=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=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:s,nextSteps:[`Retry with a child command, for example: ${s[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --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 mS(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 uS(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 pS(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(r.length>0)throw dS(e.selectedCommand,r);let o=J_.get(B(e.selectedCommand));throw o?mS(e.selectedCommand,o):uS(e.selectedCommand)}function fS(e,t){let n=aS(e,t.mergedExtensionContracts);cS(e,n);let r=lS(n,t.mergedExtensionContracts);pS(e,r);let o=e.selectedCommand?Q_.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:Nk(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 s=e.selectedAction?i.filter(m=>m.action===e.selectedAction):i,a=[...new Map(s.map(m=>Vk(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:s,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function _S(e){return new Set(Pr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function hS(e){let t=Yu,n=Pr(t),r=_S(t),o=e.filter(i=>!r.has(i.action)).map(i=>qk(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function W_(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?$k(n,e.selectedAction):e.selectedCommand?gc(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):gc(n,r);return e.runtimeOnly&&!e.selectedAction?gc(o,new Set(t.actions)):o}function gS(e,t,n){let r=hS(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?nS(W_(e,n,r),t.createRequiredOptionContracts):W_(e,n,r);return{mergedSchema:r,filteredSchema:i}}function yS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Lk(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function oh(e,t){return t.find(n=>B(n.command)===B(e))?.tier??Qo(e)}function Gi(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||oh(t,n)!=="internal"}function vS(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 vc.keys())r.add(o);return t.filter(o=>!r.has(o)&&Gi(e,o,n))}function ih(e){let t=ke.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":vc.get(n)??n}var wS=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"]]),bS=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function kS(e,t){let n=G_.get(B(e))??(e.includes(" ")?void 0:G_.get(ih(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>gt(m.command).some(u=>B(u)===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),s=o.slice(0,-1).join(" "),a=wS.get(i),c=bS.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function SS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ye))].filter(i=>i.length>0).sort((i,s)=>i.localeCompare(s)).map(i=>{let s=Pa(i,{generateFallback:!0}),a=i.split(" ")[0],c=vc.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...rh(i).map(f=>f.flag),...t.filter(f=>gt(f.command).some(_=>B(_)===B(i))).flatMap(f=>f.flags.map(_=>_.flag))]),u=(U_.get(B(i))??U_.get(c)??Ck).filter(f=>m.has(f)),p=kS(i,t);return{command:i,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:s.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...s.default_max_estimated_tokens_by_format}}:{}}})}function ES(e){return e.map(t=>({budget:Pa(t,{generateFallback:!0}),envelope:sp(t)}))}function AS(e){let t=new Map;for(let n of e){let r=np(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(","),s=t.get(i)??{commands:[],exit_codes:o};s.commands.push(n),t.set(i,s)}return[...t.values()]}function TS(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=>Gi(e,r.command,t.extensionContracts))}function CS(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 IS(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=ap);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(s=>`--${s.cli_flag}`))].sort((s,a)=>s.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Tu],services:[...Cu],policy_modes:[...Iu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...xu],trust_modes:[...Ru],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Ou],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Fd],create_modes:[...Md],close_validation_modes:[...Dd],workflow_enforcement_modes:[...Ud]},e.relationship_kind_contracts=[...Kd,...(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 RS(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 OS(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=Qk(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(dp).filter(([s])=>i.has(s)).map(([s,a])=>({command:s,default:a,brief_fields:[...lp],compact_fields:[...cp]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:s})=>({canonical:i,aliases:s})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function xS(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=eS();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function PS(e,t,n,r){e.command_summaries=SS(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Uu],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(ye))].filter(o=>La(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...ju(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(ya.map(({slots:o})=>lm(o))).size,positional_action_count:ga.length,positional_action_parents:[...new Set(ga.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:ya}:{}}}async function wc(e,t){let n=rS(e);oS(n);let r=E(process.cwd(),t.path),o=await sS(t,r,n),i=fS(n,o),s=gS(n,o,i),a=yS(n,i),c=vS(n,a,o.extensionContracts),m=CS(n,s,i,c),u=TS(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&PS(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=Zk(i.commandCatalog.filter(_=>Gi(n,_,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||IS(m,o,n),RS(m,n,s,u),OS(m,n,o,c,f),xS(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...sf],gate_triggers:[...of]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=uo.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=D_(),m.context_intents=zu(),m.read_output_dimensions=Na,m.error_codes=rp,m.command_output_contracts=ES(c),m.diagnostic_output_contracts=Gu,m.command_exit_contracts={vocabulary:tp,command_sets:AS(c)}),m}import{readFile as NS}from"node:fs/promises";import LS 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]="c64f304d-9081-5bad-8187-7bf6b65e4a07")}catch{}})();var bc="context-intents.json";function ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $S(e,t,n){if(!ji(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 sh(e,t){let n=Array.isArray(e)?e:ji(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)=>$S(r,t,o))}async function FS(e){let t=LS.join(e,bc),n;try{n=await NS(t,"utf8")}catch(o){if(Wt(o))return[];throw await Hp(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${bc}: ${i}`,{cause:o})}return sh(r,bc)}function MS(e){if(!ji(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return ji(n)?n.contextIntents??n.context_intents:void 0}function DS(e){return e.flatMap(t=>{let n=MS(t.module);return n===void 0?[]:sh(n,`package ${t.name}`)})}async function US(e){let t=await FS(e.pmRoot),n=DS(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function kc(e,t){let n=await US(e);return await Bu(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]="c2766f4e-6354-55bb-9e40-676273ee901f")}catch{}})();async function ah(e,t,n=Ku){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 jS}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]="9133d39d-b2fb-5f99-8fd3-87a7d2f8df6d")}catch{}})();var Sc="PmCliError";function GS(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function ch(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,GS(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function qi(e){if(!(e instanceof Error)||e.name!==Sc)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4c3bb78a-4b63-51ef-a854-c4520cfd3f32")}catch{}})();function Ec(e){let t=zd();for(let n of e)t.register(n);return t}function lh(e,t,n,r){return{client:t,isItemNotFoundError:o=>qi(o)&&o.exitCode===d.NOT_FOUND,getItemAt:(o,i)=>af(o,i,{pmRoot:e}),openRelationshipEventStore:o=>lf.open({pmRoot:e,nodes:o.nodes,registry:Ec(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Hd(o.nodes,o.edges,Ec(o.definitions)),analyzeRelationshipImpact:(o,i,s)=>df(o,i,s),validateRelationshipEvents:o=>{let i=new cf(o.nodes,{registry:Ec(o.definitions)});return o.events.map(s=>i.append({...s,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>mf({...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=await A(e);try{let s=await ni({pmRoot:e,filePath:ne(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${jS("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 a=>{let c=a===null?null:JSON.parse(a);if(!Ma(c).success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",d.USAGE);let m=await o.mutate(structuredClone(c));if(!Ma(m).success)throw new l("Workspace settings mutation returned invalid settings.json.",d.USAGE);return{raw:qe(c,m)?a:Lp(m),result:void 0}}});return s.changed&&o.dryRun!==!0&&await Y({path:ne(e),scope:"project",op:"extension:pm:settings"}),{changed:s.changed,dry_run:o.dryRun===!0,replayed:s.replayed===!0}}finally{Pp(e)}}}}import qS from"node:fs/promises";import X from"node:path";import KS from"node:readline/promises";import{stdin as zS,stdout as Me}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="231597cc-2166-5029-9b3a-476587a33941")}catch{}})();var Tc=Symbol.for("pm.sdk.init-invocation-cwd");var BS=()=>KS.createInterface({input:zS,output:Me});function HS(){return structuredClone(At)}var VS=["minimal","default","strict"];function mh(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: ${VS.join(", ")}`,d.USAGE)}function WS(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return pu(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${uu.join(", ")}`,d.USAGE)}}}function YS(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 Ac(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 JS(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||Ac(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),u=X.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&Ac(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),s=X.join(X.resolve(e),".agents","pm"),a=X.dirname(X.dirname(i)),c=X.resolve(i)===s?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:a,discovery:c,requested_cwd:X.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:s}:{}}:{mode:"tracker-path",tracker_root:i}}}function XS(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(Ac(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&&$t(e)!==$t(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 ${$t(e)}`,`pm init --id-prefix ${$t(t)}`]});return t}function QS(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: ${Nf.join(", ")}`,d.USAGE)}function ZS(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function uh(e,t){let n=qd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function eE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tE(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(eE).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function nE(e,t,n){let r=qo(t.schema),o=ut(e,r.files.types,mt.types),s=du(await Z(o)),a=[],c=[];for(let m of fu(n)){let u=mu(s,m);s=u.file,(u.replaced?c:a).push(u.definition.name)}return await rt({pmRoot:e,filePath:o,raw:Go(s),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:c,file:o}}async function rE(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",X.join(".agents","pm")];for(let n of t)if(await G(X.join(e,n)))return!0;return!1}async function oE(e,t,n){if(!t||n||await G(X.join(e,"settings.json"))||!await rE(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 ph(e,t){let n=[],r=[];for(let o of t){let i=o?X.join(e,o):e,s=await G(i);await qS.mkdir(i,{recursive:!0}),s?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 iE(e,t){let n=BS();try{Me.write(`pm init setup wizard (agent-optimized)
2
2
  `),Me.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
3
3
 
4
4
  `),Me.write(`1/3 Item ID prefix
@@ -8,30 +8,30 @@ import{n as pu,o as jo,p as yu,q as vu,r as ya,s as zo,t as wu,u as va,v as Bo,y
8
8
  `),Me.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
9
9
  `),Me.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
10
10
  `),Me.write(`strict: ownership blocking, strict create defaults, close validation strict.
11
- `);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=i.trim().length>0?i.trim():"minimal",a="minimal";try{a=ch(s)}catch{Me.write(`Unrecognized governance preset "${s}"; using minimal.
11
+ `);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=i.trim().length>0?i.trim():"minimal",a="minimal";try{a=mh(s)}catch{Me.write(`Unrecognized governance preset "${s}"; using minimal.
12
12
  `)}Me.write(`
13
13
  3/3 Project telemetry
14
14
  `),Me.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
15
- `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=YS(m,t);return Me.write(`
16
- `),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function nE(e){return{presetFromOption:ch(e.preset),useDefaults:e.defaults===!0,authorFromOption:BS(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:WS(e.agentGuidance),typePreset:zS(e.typePreset)}}function rE(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function oE(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function iE(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(lh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function sE(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=rE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return oE(e.settingsPath,n,e.options.force===!0,e.target),iE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await $e(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function aE(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await tE(t,At.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",s=qS();s.id_prefix=t,lh(s,i);let a=ei()?.trim()||void 0;return s.author_default=e.normalizedOptions.authorFromOption??a??"",r!==void 0&&(s.telemetry.enabled=r,s.telemetry.first_run_prompt_completed=!0),await $e(e.pmRoot,s),{settings:s,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function ah(e){return e.settingsExists?await sE(e):await aE({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function cE(e){let t=await xf({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await $e(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function lE(e,t){let n=[],r=[],o=await _u(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await J({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function dE(e){if(e.typePreset===void 0)return;let t=await QS(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await J({path:t.file,scope:"project",op:"init:type_preset"})),t}async function mE(e){let n=x(e.settings,R()).folders.filter(o=>!ma.includes(o)),r=await dh(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function uE(e){let t=X.resolve(e.tracker_root),n=X.dirname(t);return X.basename(t)==="pm"&&X.basename(n)===".agents"?X.dirname(n):e.workspace_root}async function pE(e,t,n,r){if(!e)return;let o=await Un("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=XS(o),s=i.packages.filter(a=>!a.ok).map(a=>a.alias);if(!i.installed_all||s.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${s.length>0?`: ${s.join(", ")}`:"."}`,d.GENERIC_FAILURE);return i}function fE(e){let t=r=>Zt([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function _E(e,t,n,r=mf){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function hE(e,t,n,r){if(e==null||n==="status")return;let o=await Wa(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Nr(e,t,n={}){let r=t[Ec],o=typeof r=="string"?r:process.cwd(),i=HS(o,t,e,n.workspace),s=i.pmRoot;e=VS(i.prefixArg,n.idPrefix);let a=nE(n);await eE(s,i.target.mode==="tracker-path",n.force===!0);let c=[],m=[],u=X.join(s,"settings.json"),p=await G(u),f;p&&(f=await ah({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:$t(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:i.target}));let _=await dh(s,ma);c.push(..._.createdDirs),m.push(..._.warnings),f??=await ah({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:$t(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:i.target});let{settings:h}=f,y=uE(i.target),g=await ki(y??X.dirname(s)),v=y??g,b=await cE({pmRoot:s,cwd:v??o,agentGuidanceMode:a.agentGuidanceMode,settings:h,warnings:m}),k=await lE(s,h);c.push(...k.createdDirs),m.push(...k.warnings);let T=await dE({pmRoot:s,settings:h,typePreset:a.typePreset,warnings:m});T&&(h=await A(s)),await mE({pmRoot:s,settings:h,createdDirs:c,warnings:m}),await hE(v,s,a.agentGuidanceMode,m),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await _E(s,g,m);let O=await pE(a.installBundledPackages,t,s,m),L=fE({installBundledPackages:a.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:i.target});return{ok:!0,path:s,target:i.target,settings:h,created_dirs:c,warnings:m,governance_preset:h.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...O?{installed_packages:O}:{},next_steps:L,agent_guidance:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3046466c-614c-5e2b-a156-df96fba8c483")}catch{}})();async function mh(e,t){let n=E(t??process.cwd(),e),r=await A(n);return fe(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c7a926a-46a2-560c-ae95-33b92b8c820e")}catch{}})();var gE={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function uh(e){return Object.fromEntries(xu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var ph={ctx:{action:"context"},...gE,...uh("extension"),...uh("package"),...Object.fromEntries(Pu.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="176b4ac2-2c47-50d6-beee-62e1d3dc9281")}catch{}})();function fh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yE(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Ac(e,t){let n=yE(t),r=n==="brief"?n:fh(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:fh(e.filters)?e.filters:{},projection:r}}}import{readFile as vE}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]="0a5fc27e-3f5a-59e0-998e-be5da72913dd")}catch{}})();function qi(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ce(e,t)}function _h(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Tc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function on(e,t){let n=e[t];return Array.isArray(n)?n:[]}function zn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let i=le(n,"--add");return Object.keys(i).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:i.text?.trim()||n}catch{return n}}function Cc(e){return typeof e=="object"&&e!==null&&"code"in e}function $r(e,t){if(!ft(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function wE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let r=Lt(),o=ft(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return $r(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return $r(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await vE(i,"utf8"),emptyFlag:"--file"}}catch(s){if(Cc(s)&&Wt(s))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let a=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${i}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function Ki(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await wE(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Lr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function gh(e){return e==="comments"?"--stdin":"--add -"}function bE(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=gh(t.collectionKey),i=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${r}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${i} ${o}`,`${i} --add text=${r}`]})}function kE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${gh(e.collectionKey)}`]})}function SE(e,t,n,r,o,i){let s=on(e.metadata,t),a=o?s.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(s.push(i({created_at:S(),author:n,text:r})),e.metadata[t]=s,{changedFields:[t],entryIndex:s.length})}async function Bn(e,t,n,r){kE(r,t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=x(i,R()),a=yr(t.limit);if(r.input.mode==="list"){let h=await q(o,e,i.id_prefix,i.item_format,s.type_to_folder);if(!h)throw new l(`Item ${e} not found`,d.NOT_FOUND);let y=await ie(h,{schema:i.schema}),g=on(y.document.metadata,r.collectionKey);return ji(h.id,r.collectionKey,g,a,t.includeMeta===!0)}let c=C(t.author,i.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,y;try{y=await se({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=on(v.metadata,r.collectionKey),k=hh(r.input.index,b.length,r.collectionKey);return _h(b[k],"deleted"),b.splice(k,1),v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){Lr(v,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return ji(y.item.id,r.collectionKey,g,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";bE(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let h=r.editOp??r.op,y;try{y=await se({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=on(v.metadata,r.collectionKey),k=hh(r.input.index,b.length,r.collectionKey),T=b[k];return _h(T,"edited"),b[k]={...T,text:u,edited_at:S()},v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){Lr(v,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return ji(y.item.id,r.collectionKey,g,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:g[r.input.index-1]},t.fullHistory===!0)}let p,f=0;try{p=await se({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let y=SE(h,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(h){Lr(h,r.conflictGuidance)}let _=on(p.item,r.collectionKey);return ji(p.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function hh(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${i})`,d.USAGE)}return e-1}function EE(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function ji(e,t,n,r,o,i,s=!1){let a=i===void 0||s?Tc(n,i!==void 0&&s?void 0:r):i.entry===void 0?[]:[i.entry],c=i!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...EE(t,i,c)}}import{readFile as AE}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]="147e3cfb-45ad-5600-b27c-18e6f80ffb80")}catch{}})();async function Ic(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",ft(e))??"",emptyFlag:"--add"};if(r)return $r(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",d.USAGE);if(s==="-")return $r(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await AE(s,"utf8"),emptyFlag:"--file"}}catch(a){if(Cc(a)&&Wt(a))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${s}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function TE(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(i){if(await Ic(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let c=await Ic(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let s=await Ic(e,t);return s===void 0?{mode:"list"}:{mode:s.emptyFlag==="--add"?"add":s.emptyFlag==="--stdin"?"stdin":"file",value:s.value,emptyFlag:s.emptyFlag}}async function yh(e,t,n){let r=Lt(),o=await TE(t,r),i=o.mode==="add"||o.mode==="edit",s=o.value??"";return Bn(e,t,n,{input:{...o,rawValue:t.add??s,value:i?zn(s,{stripPlainTextPrefix:!0}):s},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="615d2313-d6ef-51e0-93eb-6234b2f0e6cd")}catch{}})();var vh=new Set(["item_format"]),wh=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),CE=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),IE=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),RE={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function OE(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(vh.has(t)||wh.has(t)||CE.has(t)||t==="context")return t}function xE(e){let t=e.trim().toLowerCase();return RE[t]??e}function bh(e,t){let n=OE(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:vh.has(n)?{routable:!0,flag:"format",value:t}:wh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:IE.has(n)?xE(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="326e677a-c427-55e0-aad9-5204ea59661b")}catch{}})();var PE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Rc=128,NE=1e4;function kh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>Rc)throw new Error(`A legacy author must contain 1-${Rc} characters.`);return t}function LE(e){let t=e?.trim().toLowerCase();if(!t||!PE.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function $E(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function FE(e,t){let n=new Set;for(let r of(e??[]).slice(0,NE)){let o=r.trim().slice(0,Rc);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function ME(e,t){let n=kh(t.legacy_author),r=LE(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function DE(e,t){if(t.operation==="add")return ME(e,t);if(t.operation==="remove"){let r=kh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Oc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Sh(e,t){let n=e?.version??1,r={...e?.aliases},o=DE(r,t),i={version:o?n+1:n,aliases:$E(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:FE(t.observed_authors,i.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6fdd2eb-5447-5b10-af5b-33765e341bd2")}catch{}})();var Eh=["project","global"],yt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},UE=Object.keys(yt).map(e=>yt[e][0]),GE=Object.fromEntries(Object.keys(yt).flatMap(e=>yt[e].map(t=>[t,e]))),jE={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},qE=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],KE=new Set(["metadata_required_fields",...qE]),zE=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),BE=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),HE=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),VE=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),WE=new Set(["governance_preset","governance_create_default_type"]),Rh=e=>KE.has(e),YE=e=>HE.has(e),JE=e=>VE.has(e),XE=e=>WE.has(e);function xc(e){return e==="definition_of_done"||Rh(e)}function QE(e){if(Eh.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${Eh.join(", ")}`,d.USAGE)}function ZE(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Te({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function eA(e){let t=GE[e];if(t)return t;let n=ya.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${UE.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function tA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function nA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function Oh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function rA(e){return Nc(e,"test-result-tracking")}function Nc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function xh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Lc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function Ph(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function Nh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function Lh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function $h(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function Fh(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function Mh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function Dh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}var oA={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Ah(e,t){let n=oA[e];if(n)return Nc(t,n);switch(e){case"history_missing_stream_policy":return Oh(t);case"sprint_release_format_policy":return za(t);case"parent_reference_policy":case"governance_parent_reference_policy":return pi(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Lc(t);case"governance_preset":return Ph(t);case"governance_ownership_enforcement":return Nh(t);case"governance_create_mode_default":return Lh(t);case"governance_close_validation_default":return $h(t);case"governance_require_close_reason":return Dh(t);case"governance_workflow_enforcement":return Fh(t);case"governance_force_required_for_stale_lock":return Mh(t);case"telemetry_tracking":return xh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Th={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},iA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function sA(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>Th[i]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${iA.join(", ")}`,d.USAGE);return[...new Set(r.map(i=>Th[i]))].sort((i,s)=>i.localeCompare(s))}function aA(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new l(`Config set ${yt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${yt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function cA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function lA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return eA(t)}function Uh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var dA={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Oc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function $c(e,t){return dA[t](e)}function Ie(e,t){return t.length===0?e:{...e,warnings:t}}async function mA(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):ct(n),o=ue(r);return e==="project"&&await I(r),{pmRoot:r,settingsPath:o}}function uA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function Ch(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function pA(e,t,n,r,o){let i=!1,s=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!da.includes(c))throw new l(`Context --default-depth must be one of ${da.join("|")}`,d.USAGE);s.default_depth!==c&&(s.default_depth=c,i=!0)}if(t.activityLimit!==void 0){let c=Ch(t.activityLimit,"--activity-limit");s.activity_limit!==c&&(s.activity_limit=c,i=!0)}if(t.staleThresholdDays!==void 0){let c=Ch(t.staleThresholdDays,"--stale-threshold-days");s.stale_threshold_days!==c&&(s.stale_threshold_days=c,i=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=uA(m);if(u!==void 0){let p=c;s.sections[p]!==u&&(s.sections[p]=u,i=!0)}}return i&&await $e(n.pmRoot,e,"config:set:context"),Ie({scope:r,key:"context",context_settings:{default_depth:s.default_depth,activity_limit:s.activity_limit,stale_threshold_days:s.stale_threshold_days,sections:{...s.sections}},settings_path:n.settingsPath,changed:i},o)}function fA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function _A(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return fA(t,o,i);Uh(n);let s=bh(n,o);if(!s.routable)throw new l(s.reason,d.USAGE);if(s.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...i,criterion:s.values}}if(s.flag==="format")return{...i,format:s.value};if(i.policy!==void 0&&Ah(n,i.policy)!==Ah(n,s.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,d.USAGE);return{...i,policy:s.value}}function hA(e){let t=Object.keys(yt).map(r=>({key:r,aliases:yt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":xc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:xc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:jE[r],value:$c(e.settings,r)})),n=ya.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:va(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Ie({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function gA(e){let t=Object.fromEntries(Object.keys(yt).map(n=>[n,$c(e.settings,n)]));return Ie({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function yA(e,t){let n=$c(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Ie({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Ie({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Ie({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Ie({...r,criteria:n},e.warnings):Ie({...r,policy:n},e.warnings)}async function vA(e,t,n,r){if(t==="get"){let a=va(e.settings,n);return Ie({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let i=wu(n,o);if(!i.ok)throw new l(i.error.message,d.USAGE);let s=Bo(e.settings,n,i.parsed.value);return s&&await $e(e.target.pmRoot,e.settings,`config:set:${n.path}`),Ie({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:s},e.warnings)}async function Q(e,t,n){t&&await $e(e.target.pmRoot,e.settings,n)}function Ih(e,t,n){return e!==n||t!==n}function de(e,t,n,r){return Ie({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Pc(e,t,n,r){return Ie({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function wA(e,t){let n=nA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let i=x(e.settings,R()),s=await Yp(e.target.pmRoot,n,"config:set:item_format:migrate",i.type_to_folder,e.settings.schema);o={target_format:s.target_format,scanned:s.scanned,migrated:s.migrated,removed:s.removed,warnings:s.warnings},e.settings.item_format=n,await $e(e.target.pmRoot,e.settings,"config:set:item_format")}return Ie({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function bA(e,t,n){if(t==="history_missing_stream_policy"){let i=Oh(n.policy),s=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await Q(e,s,"config:set:history_missing_stream_policy"),de(e,t,e.settings.history.missing_stream,s)}if(t==="sprint_release_format_policy"){let i=za(n.policy),s=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await Q(e,s,"config:set:sprint_release_format_policy"),de(e,t,e.settings.validation.sprint_release_format,s)}if(t==="parent_reference_policy"){let i=pi(n.policy),s=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await Q(e,s,"config:set:parent_reference_policy"),de(e,t,e.settings.validation.parent_reference,s)}let r=Lc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Q(e,o,"config:set:metadata_validation_profile"),de(e,t,e.settings.validation.metadata_profile,o)}async function kA(e,t,n){if(t==="metadata_required_fields"){let a=sA(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await Q(e,c,"config:set:metadata_required_fields"),Pc(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],i=aA(t,n.criterion,n.clearCriteria),s=i.length!==o.length||i.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...i),await Q(e,s,`config:set:${t}`),Pc(e,t,[...o],s)}async function SA(e,t,n){if(t==="governance_preset"){let c=Ph(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Q(e,m,"config:set:governance_preset"),de(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Q(e,c,"config:set:governance_create_default_type"),de(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let i=x(e.settings,R()),s=be(o,i);if(!s)throw new l(Ot(o,i.types,xt(e.target.pmRoot,e.settings.schema)),d.USAGE);let a=e.settings.governance.create_default_type!==s;return e.settings.governance.create_default_type=s,await Q(e,a,"config:set:governance_create_default_type"),de(e,t,e.settings.governance.create_default_type,a)}async function EA(e,t,n){if(t==="governance_ownership_enforcement"){let i=Nh(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await Q(e,s,"config:set:governance_ownership_enforcement"),de(e,t,e.settings.governance.ownership_enforcement,s)}if(t==="governance_create_mode_default"){let i=Lh(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await Q(e,s,"config:set:governance_create_mode_default"),de(e,t,e.settings.governance.create_mode_default,s)}let r=$h(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Q(e,o,"config:set:governance_close_validation_default"),de(e,t,e.settings.governance.close_validation_default,o)}async function AA(e,t,n){if(t==="governance_parent_reference_policy"){let i=pi(n.policy),s=e.settings.governance.preset!=="custom"||Ih(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await Q(e,s,"config:set:governance_parent_reference_policy"),de(e,t,e.settings.governance.parent_reference,s)}if(t==="governance_metadata_validation_profile"){let i=Lc(n.policy),s=e.settings.governance.preset!=="custom"||Ih(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await Q(e,s,"config:set:governance_metadata_validation_profile"),de(e,t,e.settings.governance.metadata_profile,s)}let r=Fh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Q(e,o,"config:set:governance_workflow_enforcement"),de(e,t,e.settings.governance.workflow_enforcement,o)}async function TA(e,t,n){if(t==="governance_require_close_reason"){let a=Dh(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Q(e,c,"config:set:governance_require_close_reason"),de(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=Mh(n.policy)==="enabled",i=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await Q(e,i,"config:set:governance_force_required_for_stale_lock"),de(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",i)}async function CA(e,t,n){if(t==="test_result_tracking"){let a=rA(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Q(e,c,"config:set:test_result_tracking"),de(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=Nc(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Q(e,c,"config:set:untrusted_linked_test_execution"),de(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=xh(n.policy)==="enabled",i=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Q(e,i,"config:set:telemetry_tracking"),de(e,t,e.settings.telemetry.enabled?"enabled":"disabled",i)}async function IA(e,t,n){let r=tA(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,s)=>i!==e.settings.workflow.definition_of_done[s]);return e.settings.workflow.definition_of_done=r,await Q(e,o,"config:set:definition_of_done"),Pc(e,t,[...e.settings.workflow.definition_of_done],o)}function RA(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function OA(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function xA(e,t){let{operation:n,dryRun:r}=RA(t.policy),o=OA(n,t.value),i;try{i=Sh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(s){throw new l(s.message,d.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await Q(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`)),Ie({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Oc(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function PA(e,t,n){if(n.clearCriteria===!0&&!xc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?wA(e,n):t==="context"?pA(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?xA(e,n):t==="definition_of_done"?IA(e,t,n):Rh(t)?kA(e,t,n):zE.has(t)?CA(e,t,n):BE.has(t)?TA(e,t,n):YE(t)?EA(e,t,n):JE(t)?AA(e,t,n):XE(t)?SA(e,t,n):bA(e,t,n)}async function Gh(e,t,n,r,o,i){let s=QE(e),a=ZE(t),c=a==="get"||a==="set"?zo(n):void 0,m=c?void 0:lA(a,n),u=_A(a,n,m,c,i,r),p=await mA(s,o),{settings:f,metadata:_,warnings:h}=await Pp(p.pmRoot),y={scope:s,target:p,settings:f,metadata:_,warnings:cA(h)};return c?vA(y,a,c,u):a==="list"?hA(y):a==="export"?gA(y):(Uh(m),a==="get"?yA(y,m):PA(y,m,u))}import qh from"node:fs/promises";import Kh 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]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function NA(e,t,n){let r=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||r.has(s))continue;r.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function LA(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function jh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return NA(t.ids,n,t.minEntries)}return LA(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1dede7b7-eeea-520d-97ce-a71687d93bc2")}catch{}})();function $A(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),s=Fn(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new l(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,d.USAGE);let a=i-s-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,d.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function FA(e,t){let n=fr(),r=fr();for(let o=0;o<e.length;o+=1){let i=e[o];n=Mn(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function MA(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:kp.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Ga(hr(e.document),r,pt(n.hash_algorithm)).includes(n.after_hash))}}function DA(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function UA(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function GA(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=FA(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Fn(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=Le({hashAlgorithm:pt(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:tt(fr()),after:tt(t),message:UA(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:Sp(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[Ep({...s,before_hash:Ga(fr(),i.item_hash_version??1,pt(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||a.push(Le({nowIso:S(),author:e.author,op:"history_compact",before:tt(n),after:tt(n),message:DA(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Fc(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await Sr(n.path),s=await tn(r,e,o,i.type_to_folder);return Ri({pmRoot:r,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>jA(s,t,a)})}function jA(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);let s=$A(t.before,o),a=s.compactCount>0,c=!!t.dryRun,m=n.author,u=[];a||u.push("history_compact_noop_before_boundary");let p=MA(n.loadedItem,o);p.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:h}=GA({historyEntries:o,boundary:s,changed:a,dryRun:c,author:m,options:t}),y=Fn(o,!0),g=s.retainedCount>0&&y!==null?y+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:v,warnings:b})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:g},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:h,verify_ok:v.ok,verify_errors:v.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:p.matchedChainBefore},warnings:[...new Set([...u,...b])].sort((k,T)=>k.localeCompare(T)),generated_at:S()})}}var qA=3;function KA(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,d.USAGE)}let t=ui(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:mi(t)}}function zh(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function zA(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function BA(e){let t=F(e.settings.schema),n=vi(t),r=await fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),i=Kh.join(e.pmRoot,"history"),s=[],a=[];if(!await G(i))return{candidates:s,preselectionErrors:a};let c=(await qh.readdir(i)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Kh.join(i,m),p=m.slice(0,-6);try{let f=await qh.readFile(u,"utf8");await In({path:u,scope:"project"}),s.push({id:p,entries:zA(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function HA(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Fc(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function Bh(e,t){let n=KA(e),{pmRoot:r,settings:o,typeRegistry:i}=await Sr(t.path),{candidates:s,preselectionErrors:a}=await BA({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??qA,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=jh(s,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),h=!!e.dryRun,y=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let v of _){let b=await HA({row:v,options:n,dryRun:h,global:t});if(y.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:h,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:g,results:y,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41f0e5cd-5974-5451-9f34-2aec1d8df07c")}catch{}})();function Hh(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return a_(n,t),t?Oi(e.options,e.global):Gt(n,e.options,e.global)}function Vh(e){let t=e.options.ids,n=ui(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:mi(n),o=Fe(e.options.allOver??e.options.all_over,"history-compact allOver"),i=Fe(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(s==="closed"||s==="all-streams")&&a.push(s);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return zh(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?Fc(e.id,{before:w(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global):Bh({ids:r,scope:m,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}import Mc 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]="9d9d625b-152d-5417-8702-6e0e45839500")}catch{}})();function Wh(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function VA(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function WA(e){let t=e.trim();if(t.length===0)throw new l("history-redact --regex requires a non-empty pattern.",d.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=VA(t.slice(o+1)))}if(n.length===0)throw new l("history-redact --regex cannot use an empty pattern.",d.USAGE);try{new RegExp(n,r)}catch{throw new l("Invalid --regex value; provide a valid JavaScript regular expression.",d.USAGE)}return{kind:"regex",source:n,flags:r}}function YA(e,t){let n=[...new Set(Wh(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=[...new Set(Wh(t).map(i=>i.trim()))].filter(i=>i.length>0).map(WA),o=[...n,...r];if(o.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",d.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function JA(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function XA(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function Jh(e,t,n){let r=e,o=0;for(let i of t){let s=i.kind==="literal"?JA(r,i.value,n):XA(r,i,n);r=s.value,o+=s.replacements}return{value:r,replacements:o}}function zi(e,t,n){if(typeof e=="string")return Jh(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(i=>{let s=zi(i,t,n);return r+=s.replacements,s.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,s]of Object.entries(e)){let a=zi(s,t,n);r+=a.replacements,o[i]=a.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function Yh(e,t,n){let r=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=zi(i.value,t,n);return r+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:r}}function QA(e){let t=structuredClone(Ua),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];_r(t,void 0,pt(i.hash_algorithm))!==i.before_hash&&(n+=1),t=Mn(t,i.patch,o+1,i.op),_r(t,void 0,pt(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function ZA(e,t,n){let r=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let m=Jh(e.message,t,n);s=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let a=Yh(e.patch,t,n);r+=a.replacements,o||=a.replacements>0;let c=e.reanchor_evidence?.map(m=>{let u=m.patch?Yh(m.patch,t,n):{patch:void 0,replacements:0},p=m.record?zi(m.record,t,n):{value:void 0,replacements:0};r+=u.replacements,r+=p.replacements;let f=u.replacements>0||p.replacements>0;if(o||=f,!f)return m;i=!0;let{patch:_,record:h,record_hash:y,record_hash_version:g,...v}=m;return u.replacements>0?v:{...v,patch:m.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function eT(e,t,n){let r=structuredClone(Ua),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let c=e[a],m=Ap(c);if(!m.ok)throw new l(`history-redact refuses invalid immutable record ${a+1} (${m.error}).`,d.GENERIC_FAILURE);let u=ZA(c,t,n);i+=u.replacements,u.changed&&(o+=1);let p=_r(r,void 0,pt(c.hash_algorithm));r=Mn(r,u.entry.patch,a+1,u.entry.op);let f=_r(r,void 0,pt(c.hash_algorithm));s.push(Tp(c,{...u.entry,before_hash:p,after_hash:f},{retainPriorRecord:u.changed,retainPriorRecordHash:!u.changed}))}return{entries:s,finalDocument:r,entriesChanged:o,replacements:i}}function tT(e){return Object.keys(e.metadata).length>0}function nT(e){if(!tT(e.finalDocument))return{raw:null,path:null,document:null};let t=et(tt(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",d.USAGE);return{document:t,path:lt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Be(t,{format:"toon",schema:e.settings.schema})}}function rT(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function oT(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??tt(e.rewritten.finalDocument);return t.push(Le({nowIso:S(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function iT(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Ft(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await te(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Mc.rm(e.currentItem.path,{force:!0}),await te(e.subject.historyPath,Ip(e.rewrittenEntries))}catch(c){try{await sT(e.subject.historyPath,n,o,i)}finally{await Da(e.subject.historyPath)}throw c}await Da(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Mt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await aT(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function sT(e,t,n,r){t===null?await Mc.rm(e,{force:!0}):await te(e,t);for(let o of n){let i=r.get(o);i===void 0?await Mc.rm(o,{force:!0}):await te(o,i)}}async function aT(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await J({path:o,scope:"project",op:"history_redact"}));return n.push(...await J({path:e,scope:"project",op:"history_redact:history"})),n}async function Xh(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await Sr(n.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,m=YA(t.literal,t.regex),u=await tn(r,e,o,i.type_to_folder);return Ri({pmRoot:r,subject:u,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:p=>cT({pmRoot:r,subject:u,settings:o,typeRegistry:i,options:t,rules:m,replacement:c,replacementIsDefault:a},p)})}function cT(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:s,rules:a,replacement:c,replacementIsDefault:m}=e,u=t.entries,p=QA(u),f=eT(u,a,c),_=p.hashMismatchesBefore+p.hashMismatchesAfter,h=!!s.dryRun,y=f.replacements>0,g=[];_>0&&g.push(`history_redact_preexisting_hash_mismatches:${_}`),y||g.push("history_redact_no_matches");let v={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=nT({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),k=(v.path??null)!==(b.path??null)||(v.raw??null)!==(b.raw??null),T=t.author,O=rT(s,f),{rewrittenEntries:L,auditEntryAdded:$}=oT({rewritten:f,dryRun:h,changed:y,nextItemDocument:b.document,author:T,message:O});return{changed:y,rewrittenEntries:L,...iT({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:v,nextItem:b,author:T,rewrittenEntries:L}),report:({verification:K,warnings:Y})=>({id:r.id,dry_run:h,changed:y,patterns:{literal_count:a.filter(z=>z.kind==="literal").length,regex_count:a.filter(z=>z.kind==="regex").length,total_count:a.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:u.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:p.hashMismatchesBefore,hash_mismatches_after:p.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:$,verify_ok:K.ok,verify_errors:K.errors},item:{existed_before:v.path!==null,exists_after:b.path!==null,path_before:v.path,path_after:b.path,changed:k},warnings:[...new Set([...g,...Y])].sort((z,me)=>z.localeCompare(me)),generated_at:S()})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="039acb6e-090c-554f-9323-29e44496552d")}catch{}})();async function Qh(e,t,n){return Bn(e,t,n,{input:await Ki(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>zn(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="663579ae-aebb-524c-81c9-9aed44e40f35")}catch{}})();async function Zh(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Lt(),o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=C(t.author,i.author_default),c=(await r.resolveValue(t.body,"--body",$p(t,"body"))).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let m=await se({pmRoot:o,settings:i,id:e,op:"append",author:s,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
15
+ `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=ZS(m,t);return Me.write(`
16
+ `),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function sE(e){return{presetFromOption:mh(e.preset),useDefaults:e.defaults===!0,authorFromOption:YS(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:QS(e.agentGuidance),typePreset:WS(e.typePreset)}}function aE(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function cE(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function lE(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(uh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function dE(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=aE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return cE(e.settingsPath,n,e.options.force===!0,e.target),lE({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await $e(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function mE(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await iE(t,At.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",s=HS();s.id_prefix=t,uh(s,i);let a=ei()?.trim()||void 0;return s.author_default=e.normalizedOptions.authorFromOption??a??"",r!==void 0&&(s.telemetry.enabled=r,s.telemetry.first_run_prompt_completed=!0),await $e(e.pmRoot,s),{settings:s,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function dh(e){return e.settingsExists?await dE(e):await mE({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function uE(e){let t=await Lf({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await $e(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function pE(e,t){let n=[],r=[],o=await gu(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await Y({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function fE(e){if(e.typePreset===void 0)return;let t=await nE(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await Y({path:t.file,scope:"project",op:"init:type_preset"})),t}async function _E(e){let n=x(e.settings,R()).folders.filter(o=>!pa.includes(o)),r=await ph(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function hE(e){let t=X.resolve(e.tracker_root),n=X.dirname(t);return X.basename(t)==="pm"&&X.basename(n)===".agents"?X.dirname(n):e.workspace_root}async function gE(e,t,n,r){if(!e)return;let o=await Un("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=tE(o),s=i.packages.filter(a=>!a.ok).map(a=>a.alias);if(!i.installed_all||s.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${s.length>0?`: ${s.join(", ")}`:"."}`,d.GENERIC_FAILURE);return i}function yE(e){let t=r=>Zt([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function vE(e,t,n,r=ff){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function wE(e,t,n,r){if(e==null||n==="status")return;let o=await Xa(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Nr(e,t,n={}){let r=t[Tc],o=typeof r=="string"?r:process.cwd(),i=JS(o,t,e,n.workspace),s=i.pmRoot;e=XS(i.prefixArg,n.idPrefix);let a=sE(n);await oE(s,i.target.mode==="tracker-path",n.force===!0);let c=[],m=[],u=X.join(s,"settings.json"),p=await G(u),f;p&&(f=await dh({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:$t(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:i.target}));let _=await ph(s,pa);c.push(..._.createdDirs),m.push(..._.warnings),f??=await dh({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:$t(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:i.target});let{settings:h}=f,y=hE(i.target),g=await Si(y??X.dirname(s)),v=y??g,b=await uE({pmRoot:s,cwd:v??o,agentGuidanceMode:a.agentGuidanceMode,settings:h,warnings:m}),k=await pE(s,h);c.push(...k.createdDirs),m.push(...k.warnings);let T=await fE({pmRoot:s,settings:h,typePreset:a.typePreset,warnings:m});T&&(h=await A(s)),await _E({pmRoot:s,settings:h,createdDirs:c,warnings:m}),await wE(v,s,a.agentGuidanceMode,m),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await vE(s,g,m);let O=await gE(a.installBundledPackages,t,s,m),L=yE({installBundledPackages:a.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:i.target});return{ok:!0,path:s,target:i.target,settings:h,created_dirs:c,warnings:m,governance_preset:h.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...O?{installed_packages:O}:{},next_steps:L,agent_guidance:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3046466c-614c-5e2b-a156-df96fba8c483")}catch{}})();async function fh(e,t){let n=E(t??process.cwd(),e),r=await A(n);return fe(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c7a926a-46a2-560c-ae95-33b92b8c820e")}catch{}})();var bE={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function _h(e){return Object.fromEntries(Nu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var hh={ctx:{action:"context"},...bE,..._h("extension"),..._h("package"),...Object.fromEntries(Lu.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="176b4ac2-2c47-50d6-beee-62e1d3dc9281")}catch{}})();function gh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kE(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Cc(e,t){let n=kE(t),r=n==="brief"?n:gh(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:gh(e.filters)?e.filters:{},projection:r}}}import{readFile as SE}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]="0a5fc27e-3f5a-59e0-998e-be5da72913dd")}catch{}})();function zi(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ce(e,t)}function yh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Ic(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function on(e,t){let n=e[t];return Array.isArray(n)?n:[]}function zn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let i=de(n,"--add");return Object.keys(i).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:i.text?.trim()||n}catch{return n}}function Rc(e){return typeof e=="object"&&e!==null&&"code"in e}function $r(e,t){if(!ft(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function EE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let r=Lt(),o=ft(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return $r(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return $r(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await SE(i,"utf8"),emptyFlag:"--file"}}catch(s){if(Rc(s)&&Wt(s))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let a=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${i}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function Bi(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await EE(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Lr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function wh(e){return e==="comments"?"--stdin":"--add -"}function AE(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=wh(t.collectionKey),i=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${r}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${i} ${o}`,`${i} --add text=${r}`]})}function TE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${wh(e.collectionKey)}`]})}function CE(e,t,n,r,o,i){let s=on(e.metadata,t),a=o?s.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(s.push(i({created_at:S(),author:n,text:r})),e.metadata[t]=s,{changedFields:[t],entryIndex:s.length})}async function Bn(e,t,n,r){TE(r,t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=x(i,R()),a=yr(t.limit);if(r.input.mode==="list"){let h=await q(o,e,i.id_prefix,i.item_format,s.type_to_folder);if(!h)throw new l(`Item ${e} not found`,d.NOT_FOUND);let y=await se(h,{schema:i.schema}),g=on(y.document.metadata,r.collectionKey);return Ki(h.id,r.collectionKey,g,a,t.includeMeta===!0)}let c=C(t.author,i.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,y;try{y=await ae({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=on(v.metadata,r.collectionKey),k=vh(r.input.index,b.length,r.collectionKey);return yh(b[k],"deleted"),b.splice(k,1),v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){Lr(v,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return Ki(y.item.id,r.collectionKey,g,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";AE(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let h=r.editOp??r.op,y;try{y=await ae({pmRoot:o,settings:i,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=on(v.metadata,r.collectionKey),k=vh(r.input.index,b.length,r.collectionKey),T=b[k];return yh(T,"edited"),b[k]={...T,text:u,edited_at:S()},v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){Lr(v,r.conflictGuidance)}let g=on(y.item,r.collectionKey);return Ki(y.item.id,r.collectionKey,g,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:g[r.input.index-1]},t.fullHistory===!0)}let p,f=0;try{p=await ae({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let y=CE(h,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(h){Lr(h,r.conflictGuidance)}let _=on(p.item,r.collectionKey);return Ki(p.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function vh(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${i})`,d.USAGE)}return e-1}function IE(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Ki(e,t,n,r,o,i,s=!1){let a=i===void 0||s?Ic(n,i!==void 0&&s?void 0:r):i.entry===void 0?[]:[i.entry],c=i!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...IE(t,i,c)}}import{readFile as RE}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]="147e3cfb-45ad-5600-b27c-18e6f80ffb80")}catch{}})();async function Oc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",ft(e))??"",emptyFlag:"--add"};if(r)return $r(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",d.USAGE);if(s==="-")return $r(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await RE(s,"utf8"),emptyFlag:"--file"}}catch(a){if(Rc(a)&&Wt(a))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${s}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function OE(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(i){if(await Oc(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let c=await Oc(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let s=await Oc(e,t);return s===void 0?{mode:"list"}:{mode:s.emptyFlag==="--add"?"add":s.emptyFlag==="--stdin"?"stdin":"file",value:s.value,emptyFlag:s.emptyFlag}}async function bh(e,t,n){let r=Lt(),o=await OE(t,r),i=o.mode==="add"||o.mode==="edit",s=o.value??"";return Bn(e,t,n,{input:{...o,rawValue:t.add??s,value:i?zn(s,{stripPlainTextPrefix:!0}):s},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="615d2313-d6ef-51e0-93eb-6234b2f0e6cd")}catch{}})();var kh=new Set(["item_format"]),Sh=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),xE=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),PE=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),NE={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function LE(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(kh.has(t)||Sh.has(t)||xE.has(t)||t==="context")return t}function $E(e){let t=e.trim().toLowerCase();return NE[t]??e}function Eh(e,t){let n=LE(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:kh.has(n)?{routable:!0,flag:"format",value:t}:Sh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:PE.has(n)?$E(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="326e677a-c427-55e0-aad9-5204ea59661b")}catch{}})();var FE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,xc=128,ME=1e4;function Ah(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>xc)throw new Error(`A legacy author must contain 1-${xc} characters.`);return t}function DE(e){let t=e?.trim().toLowerCase();if(!t||!FE.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function UE(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function GE(e,t){let n=new Set;for(let r of(e??[]).slice(0,ME)){let o=r.trim().slice(0,xc);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function jE(e,t){let n=Ah(t.legacy_author),r=DE(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function qE(e,t){if(t.operation==="add")return jE(e,t);if(t.operation==="remove"){let r=Ah(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Pc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Th(e,t){let n=e?.version??1,r={...e?.aliases},o=qE(r,t),i={version:o?n+1:n,aliases:UE(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:GE(t.observed_authors,i.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6fdd2eb-5447-5b10-af5b-33765e341bd2")}catch{}})();var Ch=["project","global"],yt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},KE=Object.keys(yt).map(e=>yt[e][0]),zE=Object.fromEntries(Object.keys(yt).flatMap(e=>yt[e].map(t=>[t,e]))),BE={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},HE=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],VE=new Set(["metadata_required_fields",...HE]),WE=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),YE=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),JE=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),XE=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),QE=new Set(["governance_preset","governance_create_default_type"]),Ph=e=>VE.has(e),ZE=e=>JE.has(e),eA=e=>XE.has(e),tA=e=>QE.has(e);function Nc(e){return e==="definition_of_done"||Ph(e)}function nA(e){if(Ch.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${Ch.join(", ")}`,d.USAGE)}function rA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Te({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function oA(e){let t=zE[e];if(t)return t;let n=wa.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${KE.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function iA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function sA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function Nh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function aA(e){return $c(e,"test-result-tracking")}function $c(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Lh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Fc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function $h(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function Fh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function Mh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function Dh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function Uh(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function Gh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function jh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}var cA={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Ih(e,t){let n=cA[e];if(n)return $c(t,n);switch(e){case"history_missing_stream_policy":return Nh(t);case"sprint_release_format_policy":return Va(t);case"parent_reference_policy":case"governance_parent_reference_policy":return fi(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Fc(t);case"governance_preset":return $h(t);case"governance_ownership_enforcement":return Fh(t);case"governance_create_mode_default":return Mh(t);case"governance_close_validation_default":return Dh(t);case"governance_require_close_reason":return jh(t);case"governance_workflow_enforcement":return Uh(t);case"governance_force_required_for_stale_lock":return Gh(t);case"telemetry_tracking":return Lh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Rh={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},lA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function dA(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>Rh[i]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${lA.join(", ")}`,d.USAGE);return[...new Set(r.map(i=>Rh[i]))].sort((i,s)=>i.localeCompare(s))}function mA(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new l(`Config set ${yt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${yt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function uA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function pA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return oA(t)}function qh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var fA={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Pc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Mc(e,t){return fA[t](e)}function Ie(e,t){return t.length===0?e:{...e,warnings:t}}async function _A(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):lt(n),o=ne(r);return e==="project"&&await I(r),{pmRoot:r,settingsPath:o}}function hA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function Oh(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function gA(e,t,n,r,o){let i=!1,s=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!ua.includes(c))throw new l(`Context --default-depth must be one of ${ua.join("|")}`,d.USAGE);s.default_depth!==c&&(s.default_depth=c,i=!0)}if(t.activityLimit!==void 0){let c=Oh(t.activityLimit,"--activity-limit");s.activity_limit!==c&&(s.activity_limit=c,i=!0)}if(t.staleThresholdDays!==void 0){let c=Oh(t.staleThresholdDays,"--stale-threshold-days");s.stale_threshold_days!==c&&(s.stale_threshold_days=c,i=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=hA(m);if(u!==void 0){let p=c;s.sections[p]!==u&&(s.sections[p]=u,i=!0)}}return i&&await $e(n.pmRoot,e,"config:set:context"),Ie({scope:r,key:"context",context_settings:{default_depth:s.default_depth,activity_limit:s.activity_limit,stale_threshold_days:s.stale_threshold_days,sections:{...s.sections}},settings_path:n.settingsPath,changed:i},o)}function yA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function vA(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return yA(t,o,i);qh(n);let s=Eh(n,o);if(!s.routable)throw new l(s.reason,d.USAGE);if(s.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...i,criterion:s.values}}if(s.flag==="format")return{...i,format:s.value};if(i.policy!==void 0&&Ih(n,i.policy)!==Ih(n,s.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,d.USAGE);return{...i,policy:s.value}}function wA(e){let t=Object.keys(yt).map(r=>({key:r,aliases:yt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Nc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Nc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:BE[r],value:Mc(e.settings,r)})),n=wa.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:ba(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Ie({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function bA(e){let t=Object.fromEntries(Object.keys(yt).map(n=>[n,Mc(e.settings,n)]));return Ie({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function kA(e,t){let n=Mc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Ie({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Ie({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Ie({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Ie({...r,criteria:n},e.warnings):Ie({...r,policy:n},e.warnings)}async function SA(e,t,n,r){if(t==="get"){let a=ba(e.settings,n);return Ie({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let i=ku(n,o);if(!i.ok)throw new l(i.error.message,d.USAGE);let s=Bo(e.settings,n,i.parsed.value);return s&&await $e(e.target.pmRoot,e.settings,`config:set:${n.path}`),Ie({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:s},e.warnings)}async function Q(e,t,n){t&&await $e(e.target.pmRoot,e.settings,n)}function xh(e,t,n){return e!==n||t!==n}function me(e,t,n,r){return Ie({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Lc(e,t,n,r){return Ie({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function EA(e,t){let n=sA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let i=x(e.settings,R()),s=await Qp(e.target.pmRoot,n,"config:set:item_format:migrate",i.type_to_folder,e.settings.schema);o={target_format:s.target_format,scanned:s.scanned,migrated:s.migrated,removed:s.removed,warnings:s.warnings},e.settings.item_format=n,await $e(e.target.pmRoot,e.settings,"config:set:item_format")}return Ie({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function AA(e,t,n){if(t==="history_missing_stream_policy"){let i=Nh(n.policy),s=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await Q(e,s,"config:set:history_missing_stream_policy"),me(e,t,e.settings.history.missing_stream,s)}if(t==="sprint_release_format_policy"){let i=Va(n.policy),s=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await Q(e,s,"config:set:sprint_release_format_policy"),me(e,t,e.settings.validation.sprint_release_format,s)}if(t==="parent_reference_policy"){let i=fi(n.policy),s=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await Q(e,s,"config:set:parent_reference_policy"),me(e,t,e.settings.validation.parent_reference,s)}let r=Fc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Q(e,o,"config:set:metadata_validation_profile"),me(e,t,e.settings.validation.metadata_profile,o)}async function TA(e,t,n){if(t==="metadata_required_fields"){let a=dA(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await Q(e,c,"config:set:metadata_required_fields"),Lc(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],i=mA(t,n.criterion,n.clearCriteria),s=i.length!==o.length||i.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...i),await Q(e,s,`config:set:${t}`),Lc(e,t,[...o],s)}async function CA(e,t,n){if(t==="governance_preset"){let c=$h(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Q(e,m,"config:set:governance_preset"),me(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Q(e,c,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let i=x(e.settings,R()),s=be(o,i);if(!s)throw new l(Ot(o,i.types,xt(e.target.pmRoot,e.settings.schema)),d.USAGE);let a=e.settings.governance.create_default_type!==s;return e.settings.governance.create_default_type=s,await Q(e,a,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type,a)}async function IA(e,t,n){if(t==="governance_ownership_enforcement"){let i=Fh(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await Q(e,s,"config:set:governance_ownership_enforcement"),me(e,t,e.settings.governance.ownership_enforcement,s)}if(t==="governance_create_mode_default"){let i=Mh(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await Q(e,s,"config:set:governance_create_mode_default"),me(e,t,e.settings.governance.create_mode_default,s)}let r=Dh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Q(e,o,"config:set:governance_close_validation_default"),me(e,t,e.settings.governance.close_validation_default,o)}async function RA(e,t,n){if(t==="governance_parent_reference_policy"){let i=fi(n.policy),s=e.settings.governance.preset!=="custom"||xh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await Q(e,s,"config:set:governance_parent_reference_policy"),me(e,t,e.settings.governance.parent_reference,s)}if(t==="governance_metadata_validation_profile"){let i=Fc(n.policy),s=e.settings.governance.preset!=="custom"||xh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await Q(e,s,"config:set:governance_metadata_validation_profile"),me(e,t,e.settings.governance.metadata_profile,s)}let r=Uh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Q(e,o,"config:set:governance_workflow_enforcement"),me(e,t,e.settings.governance.workflow_enforcement,o)}async function OA(e,t,n){if(t==="governance_require_close_reason"){let a=jh(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Q(e,c,"config:set:governance_require_close_reason"),me(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=Gh(n.policy)==="enabled",i=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await Q(e,i,"config:set:governance_force_required_for_stale_lock"),me(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",i)}async function xA(e,t,n){if(t==="test_result_tracking"){let a=aA(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Q(e,c,"config:set:test_result_tracking"),me(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=$c(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Q(e,c,"config:set:untrusted_linked_test_execution"),me(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=Lh(n.policy)==="enabled",i=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Q(e,i,"config:set:telemetry_tracking"),me(e,t,e.settings.telemetry.enabled?"enabled":"disabled",i)}async function PA(e,t,n){let r=iA(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,s)=>i!==e.settings.workflow.definition_of_done[s]);return e.settings.workflow.definition_of_done=r,await Q(e,o,"config:set:definition_of_done"),Lc(e,t,[...e.settings.workflow.definition_of_done],o)}function NA(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function LA(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function $A(e,t){let{operation:n,dryRun:r}=NA(t.policy),o=LA(n,t.value),i;try{i=Th(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(s){throw new l(s.message,d.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await Q(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`)),Ie({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Pc(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function FA(e,t,n){if(n.clearCriteria===!0&&!Nc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?EA(e,n):t==="context"?gA(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?$A(e,n):t==="definition_of_done"?PA(e,t,n):Ph(t)?TA(e,t,n):WE.has(t)?xA(e,t,n):YE.has(t)?OA(e,t,n):ZE(t)?IA(e,t,n):eA(t)?RA(e,t,n):tA(t)?CA(e,t,n):AA(e,t,n)}async function Kh(e,t,n,r,o,i){let s=nA(e),a=rA(t),c=a==="get"||a==="set"?zo(n):void 0,m=c?void 0:pA(a,n),u=vA(a,n,m,c,i,r),p=await _A(s,o),{settings:f,metadata:_,warnings:h}=await $p(p.pmRoot),y={scope:s,target:p,settings:f,metadata:_,warnings:uA(h)};return c?SA(y,a,c,u):a==="list"?wA(y):a==="export"?bA(y):(qh(m),a==="get"?kA(y,m):FA(y,m,u))}import Bh from"node:fs/promises";import Hh 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]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function MA(e,t,n){let r=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||r.has(s))continue;r.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function DA(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function zh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return MA(t.ids,n,t.minEntries)}return DA(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1dede7b7-eeea-520d-97ce-a71687d93bc2")}catch{}})();function UA(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),s=Fn(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new l(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,d.USAGE);let a=i-s-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,d.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function GA(e,t){let n=fr(),r=fr();for(let o=0;o<e.length;o+=1){let i=e[o];n=Mn(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function jA(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Ep.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Ka(hr(e.document),r,pt(n.hash_algorithm)).includes(n.after_hash))}}function qA(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function KA(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function zA(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=GA(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Fn(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=Le({hashAlgorithm:pt(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:nt(fr()),after:nt(t),message:KA(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:Ap(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[Tp({...s,before_hash:Ka(fr(),i.item_hash_version??1,pt(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||a.push(Le({nowIso:S(),author:e.author,op:"history_compact",before:nt(n),after:nt(n),message:qA(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Dc(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await Sr(n.path),s=await tn(r,e,o,i.type_to_folder);return xi({pmRoot:r,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>BA(s,t,a)})}function BA(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);let s=UA(t.before,o),a=s.compactCount>0,c=!!t.dryRun,m=n.author,u=[];a||u.push("history_compact_noop_before_boundary");let p=jA(n.loadedItem,o);p.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:h}=zA({historyEntries:o,boundary:s,changed:a,dryRun:c,author:m,options:t}),y=Fn(o,!0),g=s.retainedCount>0&&y!==null?y+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:v,warnings:b})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:g},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:h,verify_ok:v.ok,verify_errors:v.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:p.matchedChainBefore},warnings:[...new Set([...u,...b])].sort((k,T)=>k.localeCompare(T)),generated_at:S()})}}var HA=3;function VA(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,d.USAGE)}let t=pi(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:ui(t)}}function Vh(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function WA(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function YA(e){let t=F(e.settings.schema),n=wi(t),r=await fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),i=Hh.join(e.pmRoot,"history"),s=[],a=[];if(!await G(i))return{candidates:s,preselectionErrors:a};let c=(await Bh.readdir(i)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Hh.join(i,m),p=m.slice(0,-6);try{let f=await Bh.readFile(u,"utf8");await In({path:u,scope:"project"}),s.push({id:p,entries:WA(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function JA(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Dc(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function Wh(e,t){let n=VA(e),{pmRoot:r,settings:o,typeRegistry:i}=await Sr(t.path),{candidates:s,preselectionErrors:a}=await YA({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??HA,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=zh(s,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),h=!!e.dryRun,y=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let v of _){let b=await JA({row:v,options:n,dryRun:h,global:t});if(y.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:h,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:g,results:y,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41f0e5cd-5974-5451-9f34-2aec1d8df07c")}catch{}})();function Yh(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return d_(n,t),t?Pi(e.options,e.global):Gt(n,e.options,e.global)}function Jh(e){let t=e.options.ids,n=pi(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:ui(n),o=Fe(e.options.allOver??e.options.all_over,"history-compact allOver"),i=Fe(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(s==="closed"||s==="all-streams")&&a.push(s);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return Vh(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?Dc(e.id,{before:w(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global):Wh({ids:r,scope:m,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}import Uc 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]="9d9d625b-152d-5417-8702-6e0e45839500")}catch{}})();function Xh(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function XA(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function QA(e){let t=e.trim();if(t.length===0)throw new l("history-redact --regex requires a non-empty pattern.",d.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=XA(t.slice(o+1)))}if(n.length===0)throw new l("history-redact --regex cannot use an empty pattern.",d.USAGE);try{new RegExp(n,r)}catch{throw new l("Invalid --regex value; provide a valid JavaScript regular expression.",d.USAGE)}return{kind:"regex",source:n,flags:r}}function ZA(e,t){let n=[...new Set(Xh(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=[...new Set(Xh(t).map(i=>i.trim()))].filter(i=>i.length>0).map(QA),o=[...n,...r];if(o.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",d.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function eT(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function tT(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function Zh(e,t,n){let r=e,o=0;for(let i of t){let s=i.kind==="literal"?eT(r,i.value,n):tT(r,i,n);r=s.value,o+=s.replacements}return{value:r,replacements:o}}function Hi(e,t,n){if(typeof e=="string")return Zh(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(i=>{let s=Hi(i,t,n);return r+=s.replacements,s.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,s]of Object.entries(e)){let a=Hi(s,t,n);r+=a.replacements,o[i]=a.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function Qh(e,t,n){let r=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=Hi(i.value,t,n);return r+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:r}}function nT(e){let t=structuredClone(qa),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];_r(t,void 0,pt(i.hash_algorithm))!==i.before_hash&&(n+=1),t=Mn(t,i.patch,o+1,i.op),_r(t,void 0,pt(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function rT(e,t,n){let r=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let m=Zh(e.message,t,n);s=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let a=Qh(e.patch,t,n);r+=a.replacements,o||=a.replacements>0;let c=e.reanchor_evidence?.map(m=>{let u=m.patch?Qh(m.patch,t,n):{patch:void 0,replacements:0},p=m.record?Hi(m.record,t,n):{value:void 0,replacements:0};r+=u.replacements,r+=p.replacements;let f=u.replacements>0||p.replacements>0;if(o||=f,!f)return m;i=!0;let{patch:_,record:h,record_hash:y,record_hash_version:g,...v}=m;return u.replacements>0?v:{...v,patch:m.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function oT(e,t,n){let r=structuredClone(qa),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let c=e[a],m=Cp(c);if(!m.ok)throw new l(`history-redact refuses invalid immutable record ${a+1} (${m.error}).`,d.GENERIC_FAILURE);let u=rT(c,t,n);i+=u.replacements,u.changed&&(o+=1);let p=_r(r,void 0,pt(c.hash_algorithm));r=Mn(r,u.entry.patch,a+1,u.entry.op);let f=_r(r,void 0,pt(c.hash_algorithm));s.push(Ip(c,{...u.entry,before_hash:p,after_hash:f},{retainPriorRecord:u.changed,retainPriorRecordHash:!u.changed}))}return{entries:s,finalDocument:r,entriesChanged:o,replacements:i}}function iT(e){return Object.keys(e.metadata).length>0}function sT(e){if(!iT(e.finalDocument))return{raw:null,path:null,document:null};let t=tt(nt(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",d.USAGE);return{document:t,path:dt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:He(t,{format:"toon",schema:e.settings.schema})}}function aT(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function cT(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??nt(e.rewritten.finalDocument);return t.push(Le({nowIso:S(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function lT(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Ft(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await te(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Uc.rm(e.currentItem.path,{force:!0}),await te(e.subject.historyPath,Op(e.rewrittenEntries))}catch(c){try{await dT(e.subject.historyPath,n,o,i)}finally{await ja(e.subject.historyPath)}throw c}await ja(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Mt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await mT(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function dT(e,t,n,r){t===null?await Uc.rm(e,{force:!0}):await te(e,t);for(let o of n){let i=r.get(o);i===void 0?await Uc.rm(o,{force:!0}):await te(o,i)}}async function mT(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await Y({path:o,scope:"project",op:"history_redact"}));return n.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),n}async function eg(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await Sr(n.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,m=ZA(t.literal,t.regex),u=await tn(r,e,o,i.type_to_folder);return xi({pmRoot:r,subject:u,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:p=>uT({pmRoot:r,subject:u,settings:o,typeRegistry:i,options:t,rules:m,replacement:c,replacementIsDefault:a},p)})}function uT(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:s,rules:a,replacement:c,replacementIsDefault:m}=e,u=t.entries,p=nT(u),f=oT(u,a,c),_=p.hashMismatchesBefore+p.hashMismatchesAfter,h=!!s.dryRun,y=f.replacements>0,g=[];_>0&&g.push(`history_redact_preexisting_hash_mismatches:${_}`),y||g.push("history_redact_no_matches");let v={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=sT({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),k=(v.path??null)!==(b.path??null)||(v.raw??null)!==(b.raw??null),T=t.author,O=aT(s,f),{rewrittenEntries:L,auditEntryAdded:$}=cT({rewritten:f,dryRun:h,changed:y,nextItemDocument:b.document,author:T,message:O});return{changed:y,rewrittenEntries:L,...lT({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:v,nextItem:b,author:T,rewrittenEntries:L}),report:({verification:K,warnings:J})=>({id:r.id,dry_run:h,changed:y,patterns:{literal_count:a.filter(z=>z.kind==="literal").length,regex_count:a.filter(z=>z.kind==="regex").length,total_count:a.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:u.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:p.hashMismatchesBefore,hash_mismatches_after:p.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:$,verify_ok:K.ok,verify_errors:K.errors},item:{existed_before:v.path!==null,exists_after:b.path!==null,path_before:v.path,path_after:b.path,changed:k},warnings:[...new Set([...g,...J])].sort((z,ue)=>z.localeCompare(ue)),generated_at:S()})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="039acb6e-090c-554f-9323-29e44496552d")}catch{}})();async function tg(e,t,n){return Bn(e,t,n,{input:await Bi(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>zn(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="663579ae-aebb-524c-81c9-9aed44e40f35")}catch{}})();async function ng(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Lt(),o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=C(t.author,i.author_default),c=(await r.resolveValue(t.body,"--body",Dp(t,"body"))).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let m=await ae({pmRoot:o,settings:i,id:e,op:"append",author:s,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
17
17
 
18
18
  `:"";return u.body=`${u.body.trimEnd()}${p}${c}
19
- `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.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]="86c929a6-644f-5b8e-a12b-04a73b4f4b60")}catch{}})();var lT=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function eg(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 Dc(e,t){return Uc(e,t,{operation:"close"})}function Uc(e,t,n){let r=eg(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 Gc(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"),s=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),s&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let m=new Set(i),u=o.filter(p=>!m.has(p));u.length>0?e.dependencies=u:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,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:a,warnings:[]}:{changedFields:a,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]="49e375b7-49a8-5b6f-89c8-be70d334b78f")}catch{}})();var dT=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function mT(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 tg(e){let t=[];for(let n of dT){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function ng(e,t,n={}){let r=tg(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(a=>`--${a.key.replaceAll("_","-")}`),s=["--pm-path",t,"update",e.id,...r.flatMap((a,c)=>[i[c],o[a.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:Zt(s),suggested_retry_args:s}}async function uT(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 pT(e){return typeof e!="string"||e.trim().length===0}async function fT(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,R()),s=new Map,a=async m=>{if(s.has(m))return s.get(m)??null;let u=await q(e,m,t.id_prefix,t.item_format,i.type_to_folder);if(!u)return s.set(m,null),null;let{document:p}=await ie(u,{schema:t.schema});return s.set(m,p.metadata),p.metadata},c=await a(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 uT(a,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 _T(e,t,n){return e.filter(r=>r.parent===t&&!ne(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function hT(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=Qp(e),i=t.trim().toLowerCase(),s=n.blocked_statuses;return e.filter(a=>s.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(i)).filter(({blockerIds:a})=>a.every(c=>{if(c===i)return!0;let m=r.get(c);return m!==void 0&&ne(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function gT(e,t,n,r,o,i){let s=hT(n,r,i),a=[];for(let c of s)try{let m=await se({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=i.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function yT(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 s=o.trim();s.length!==0&&(e[i]=s,n.push(i))}return n}function vT(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)pT(e[o])&&(e[o]=i,n.push(o));return n}function wT(e,t,n,r){let o=[];if(t!=="off"){let i=tg(e);if(i.length>0){let s=i.map(a=>a.label);if(t==="strict"){let a=i.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${s.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,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}:${s.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 bT(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function kT(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function ST(e,t){if(ne(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:ng(e,t.pmRoot,t.options)});let n=yT(e,t.options),r=vT(e,t.duplicateOf),o=wT(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 s=["status","closed_at",...i?["completed_at"]:[],...bT(e,t.closeReason),...n];if(Jp(e)&&(e.plan_mode="completed",s.push("plan_mode")),t.duplicateOf!==void 0){s.push("duplicate_of");for(let c of r)s.includes(c)||s.push(c)}s.push(...kT(e));let a=Gc(e,t.lifecyclePolicy);return s.push(...a.changedFields),o.push(...a.warnings),{changedFields:s,...o.length>0?{warnings:o}:{}}}async function rg(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),s=F(i.schema),a=C(n.author,i.author_default),c=x(i,R()).type_to_folder,m=await q(o,e,i.id_prefix,i.item_format,c);if(!m)throw await _t(o,e,i.id_prefix,c);let u=await fT(o,i,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??i.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Dc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=mT(n.validateClose)??i.governance.close_validation_default,h=await fe(o,i.item_format,c,void 0,i.schema),y=_T(h,m.id,s),g=S(),v=n.completedAt===void 0?g:oe(n.completedAt,new Date(g),"completed-at"),b=await se({pmRoot:o,settings:i,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(T){return ST(T.metadata,{pmRoot:o,statusRegistry:s,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:v,lifecyclePolicy:p})}}),k=_==="warn"?ng(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...k?{recovery:k}:{},warnings:[...b.warnings,...await gT(o,i,h,m.id,a,s)]}}function vt(e,t,n,r){return rg(e,t,n,r)}import ET from"fast-json-patch";import jc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="85aa928d-92b8-5f67-8482-0fe5715fef45")}catch{}})();async function og(e,t,n){let r=await zp(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:ig(n),recovered:!0}}function AT(e,t){return jp(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function ig(e){let t=Ba(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:et(tt(t))}async function TT(e,t,n,r){let o=await tn(e,t,n,r),i=o.located?await Fp({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function CT(e,t){let n=hr(e),r=hr(t),o=ET.compare(n,r),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function IT(e){let t=await s_({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>og(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function RT(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:ig(t),originalRaw:null}}function OT(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 xT(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await te(e.existingItemPath,e.resolvedOriginalRaw),await jc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await te(e.existingItemPath,e.resolvedOriginalRaw);return}await jc.rm(e.restoredItemPath,{force:!0})}async function PT(e){return[...await J({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 J({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 sn(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),s=x(i,R()),a=await TT(o,e,i,s.type_to_folder),c=a.id,{raw:m,entries:u}=await yp(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=AT(t,u),f=qp(Ba(u,p.historyIndex),p),_=Cp(f,{schema:i.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let y=(a.located?await og(a.located,i,u):null)?.raw??null,g=C(n.author,i.author_default),v=await Ae(o,c,i.locks.ttl_seconds,g,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:b,existingItemPath:k}=await IT({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:m,currentItemRawBeforeLock:y,history:u}),T="toon",O=RT(b,u),L=OT({document:O.document,author:g,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),$=CT(O.document,_),K=await vr({pmRoot:o,settings:i,operation:"restore",author:g,before:O.document,after:_});await Ho({pm_root:o,operation:"restore",before:O.document,after:_,changed_fields:$,sdk:yi({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let Y=Be(_,{format:T,schema:i.schema}),z=lt(o,_.metadata.type,c,T,s.type_to_folder),me=await Ft(o,g),re=[];try{await te(z,Y),k&&z!==k&&await jc.rm(k);let Je=Le({nowIso:S(),author:g,op:"restore",before:O.document,after:_,message:n.message,context:K.decisions.length===0?void 0:{workflow_policies:K.decisions}});try{await Pt(a.historyPath,Je)}catch(tr){throw await xT({existingItemPath:k,resolvedOriginalRaw:O.originalRaw,restoredItemPath:z}),tr}re=await Mt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:z,previousItemPath:k??void 0,document:_})}finally{await me()}let ze=await PT({restoredItemPath:z,historyPath:a.historyPath,before:O.document,after:_});Cn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:O.document.metadata.status,status:_.metadata.status,previous:Qt(O.document.metadata,$),current:Qt(_.metadata,$),changed_fields:$});let j=u[p.historyIndex],ce=Fn(u,!0);return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:ce===null?null:ce+p.historyIndex+1,entry_ts:j.ts,entry_op:j.op},changed_fields:$,warnings:[...K.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...L,...re,...ze]}}finally{await v()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aec6f8e2-5fd0-53f3-8262-c6b49741ff96")}catch{}})();var ag=1,qc="close-many",NT=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function LT(e,t){return Ir(e,t,{includePagination:!1})}function $T(e,t){return Ir(e,t)}function FT(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 MT(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 DT(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 UT(e,t){let n=F(t.schema),r=x(t,R()),o=await fe(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,s=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(s.set(a.id,a.parent),ne(a.status,n)))continue;let c=i.get(a.parent);c?c.push(a.id):i.set(a.parent,[a.id])}for(let a of i.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:i,parentByChild:s}}function sg(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),s=[],a=new Set,c=!1;for(;i!==void 0&&!a.has(i);){let m=n?.get(i);if(m!==void 0){o+=m+1;break}a.add(i),s.push(i),o+=1,i=t.get(i)}if(i!==void 0&&a.has(i)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of s.entries())n?.set(u,o-m-1)}return o}async function GT(e){let t=await oi(e.pmRoot,qc,e.rollbackId,ag),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await ii(t.items,(o,i)=>sn(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 jT(e,t,n,r,o){return e.map(i=>{let s=(t.get(i.id)??[]).filter(c=>!n.has(c)),a=!cg(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...s.length>0?{active_child_ids:s}:{}}})}async function qT(e){let t=await ri(e.pmRoot,qc,e.checkpointId,{schema_version:ag,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 KT(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 vt(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:En(o)})}}return{rows:t,closedIds:n}}function zT(e){return typeof e.rollback=="string"?e.rollback:void 0}function BT(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($T(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function HT(e){if(!LT(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${NT}). Refusing to match every item.`,d.USAGE)}function VT(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=sg(o.id,t,n)-sg(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function cg(e,t,n){return n||!ne(e.status,t)}function WT(e,t,n){return new Set(e.filter(r=>cg(r,t,n)).map(r=>r.id))}async function YT(e){HT(e.options);let t=F(e.settings.schema),n=DT(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ht(e.options.status,MT(e.options.list),e.global),{childrenByParent:i,parentByChild:s}=await UT(e.pmRoot,e.settings),a=VT(o.items,s),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,u=new Set(m.map(f=>f.id)),p=WT(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:jT(a,i,p,t,r)}}function JT(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 XT(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 qT({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 lg(e,t){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=e.dryRun===!0,i=zT(e);if(FT(e.list),i!==void 0)return BT(e,i),GT({pmRoot:n,rollbackId:i,options:e,global:t});let s=await YT({pmRoot:n,settings:r,options:e,global:t});if(o)return JT(s);let a=new Set(s.planRows.filter(v=>v.action==="close").map(v=>v.id)),c=S(),m=ni(qc,c),u=await XT({context:s,options:e,closableIds:a,checkpointId:m,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:s.validateCloseMode,force:s.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await KT({matched:s.matched,closableIds:a,reason:s.reason,closeOptions:p,global:t}),h=f.filter(v=>v.status==="closed").length,y=f.filter(v=>v.status==="skipped").length,g=f.filter(v=>v.status==="failed").length;return{...en({applied:h,skipped:y,failed:g,unmatched:s.unmatchedIds?.length??0}),mode:"apply",matched_count:s.matched.length,dry_run:!1,...s.reason!==void 0?{reason:s.reason}:{},filters:s.listed.filters,...s.validateCloseMode?{validate_close:s.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:h,skipped_count:y,failed_count:g,rows:f,ids:_,...s.unmatchedIds!==void 0?{unmatched_ids:s.unmatchedIds,unmatched_count:s.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]="64b269aa-d285-53bb-8949-b75bed767479")}catch{}})();function QT(e,t){return[...new Set([...io.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function ZT(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Kc(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),i=x(o,R()),s=await q(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await _t(r,e,o.id_prefix,i.type_to_folder);let a=await ie(s,{schema:o.schema}),c=a.document.metadata,m=S(),u=C(t.author,o.author_default),p=await gr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=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:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=Tt(R()),g=et({metadata:h,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),v=await jn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[s.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=QT(g.metadata,g.body),k=lt(r,g.metadata.type,p,o.item_format,i.type_to_folder),T=Qe(r,p),O=await Ae(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),L={metadata:{},body:""},$,K;try{let Y=await Ft(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await jn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[s.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let z=await q(r,p,o.id_prefix,o.item_format,i.type_to_folder);if(z)throw new l(`Cannot copy to ${p}: 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 ${p} already exists at ${z.itemPath}.`,recovery:{suggested_retry:`pm copy ${s.id}`}});await te(k,Be(g,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let me=Le({nowIso:m,author:u,op:"create",before:L,after:g,message:ZT(s.id,t.message)});await Pt(T,me)}catch(me){throw await Sn(k),me}K=await Mt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:k,document:g})}finally{await Y()}$=[...await J({path:k,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:L,after:g,changed_fields:b}),...await J({path:T,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:L,after:g,changed_fields:b})],Cn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Qt(g.metadata,b),changed_fields:b})}finally{await O()}return{source_id:s.id,item:structuredClone(g.metadata),changed_fields:b,warnings:[...Ti(v),...K,...$],...v===void 0?{}:{similarity_advisory:v}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4db3d1b3-68f3-5f74-b6f0-9847b3b00fc0")}catch{}})();var eC="hierarchy-integrity";async function Bi(e){let t=e.required?await Ae(e.pmRoot,eC,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]="c45ead8e-c9ed-5b59-84e5-b8e077e84010")}catch{}})();function Hi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Vi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Wi(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(oo.includes(t))return t;let n=pe(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 Yi(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]="add1928e-08d1-5ead-9a4e-0f1a9b6580fc")}catch{}})();var tC=new Set(["none","null"]);function Ji(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 Ve(e){return e===void 0?!1:tC.has(e.trim().toLowerCase())}function Xi(e,t,n){if(!Ve(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Re(e,t,n){if(!e||e.length===0||!e.some(i=>Ve(i)))return;let o=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${o}`.trim(),d.USAGE)}function Qi(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(!o.some(a=>Ve(a)))continue;if(o.filter(a=>!Ve(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca230957-d5a6-5f20-94b5-e1eeca8ca714")}catch{}})();var nC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function dg(e,t,n,r){if(nC.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Ko("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]="70971b2a-c025-50a8-918f-871fc8adfd2a")}catch{}})();var wt=["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"],rC=new Set(wt);function mg(e){return si(e,wt)}function Zi(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!rC.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[s]=i}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${wt.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]="7ea4de2f-42e2-5ef3-89b2-d15ba6eb252a")}catch{}})();var ln=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Er,lf,"FORCE_COLOR"]),ns=/^[A-Za-z_][A-Za-z0-9_]*$/,cn=["schema","tracker","auto","none"],ug=["source","isolated","snapshot"];function Mr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let 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 s=o.slice(0,i).trim(),a=o.slice(i+1);if(!ns.test(s))throw new l(`${t} env_set key "${s}" is invalid`,d.USAGE);if(ln.has(s.toUpperCase()))throw new l(`${t} env_set key "${s}" is reserved for sandbox safety`,d.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function Dr(e,t){if(!e)return;let n=Dn(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(!ns.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 rs(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 os(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(ug.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${ug.join(", ")}`,d.USAGE)}function mn(e){if(!e)return;let t=Dn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Hn(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 is(e,t){if(!e)return;let n=pe(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 ss(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 s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function as(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 s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${s}" must be numeric`,d.USAGE);r[s]=c}return Object.keys(r).length>0?r:void 0}var oC=new Set(wt);function cs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!oC.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw t(`provides key "${o}" more than once after case normalization`);n[s]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${wt.join(", ")}.`);return n}function an(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 es(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(s=>typeof s!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(s=>s.length>0);return i.length>0?i:void 0}function pg(e,t,n){let r=es(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 ts(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 sC(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:ts(n,"timeout_seconds",t),i=r===void 0?void 0:ts(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 s=o??i;if(!Number.isInteger(s)||s<=0)throw t("timeout_seconds must be a positive integer");return s}function aC(e,t){let n=an(e,"scope",t);if(n===void 0)return"project";if(!at.includes(n))throw t(`field "scope" must be one of: ${at.join(", ")}`);return n}function cC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!cs(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(!ns.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 lC(e,t){let n=es(e,"env_clear",t);if(n){for(let r of n){if(!ns.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 dC(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 mC(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=ts(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 uC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!cs(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 pC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!cs(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]=ts(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function fC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!cs(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${wt.join(", ")}.`);let o=iC(e,r),i=an(o,"command",r),s=an(o,"cmd",r);if(i!==void 0&&s!==void 0&&i!==s)throw r("command and cmd must match when both are provided");let a=i??s;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=an(o,"path",r),m=an(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 u=dn(an(o,"workspace_context_mode",r),`${n} ${t}`),p=an(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:aC(o,r),timeout_seconds:sC(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:cC(o,r),env_clear:lC(o,r),shared_host_safe:dC(o,"shared_host_safe",r),assert_stdout_contains:es(o,"assert_stdout_contains",r),assert_stdout_regex:pg(o,"assert_stdout_regex",r),assert_stderr_contains:es(o,"assert_stderr_contains",r),assert_stderr_regex:pg(o,"assert_stderr_regex",r),assert_stdout_min_lines:mC(o,r),assert_json_field_equals:uC(o,r),assert_json_field_gte:pC(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function fg(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,s)=>fC(i,o.length>1?`entry ${s+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]="0562fd00-217b-5e1f-8004-df4574f8b796")}catch{}})();var zc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Bc=[{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"}],_g=[...zc,...Bc],ls=[{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 ds(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(Ve(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 ms(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 s=new Set;if(typeof i.key=="string"&&i.key.length>0&&s.add(i.key.toLowerCase()),typeof i.metadata_key=="string"&&i.metadata_key.length>0&&s.add(i.metadata_key.toLowerCase()),typeof i.cli_flag=="string"&&i.cli_flag.length>0&&(s.add(i.cli_flag.replaceAll("-","_").toLowerCase()),s.add(i.cli_flag.toLowerCase())),Array.isArray(i.cli_aliases))for(let a of i.cli_aliases)typeof a!="string"||a.length===0||(s.add(a.replaceAll("-","_").toLowerCase()),s.add(a.toLowerCase()));if(s.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]="49f970c3-e408-52d5-bb4d-8cea0c7f8ef4")}catch{}})();function gg(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 Hc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Oe(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE,{field:r,required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var yg=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function _C(e,t){return t==="defined"?e!==void 0:!!e}function hg(e,t,n){if(!_C(e,n))return;let r=pe(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function hC(e,t,n){let r=e?oe(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 gC(e){return Array.from(new Set(Hc(e).map(t=>Oe(t.toLowerCase(),Ud,"event weekday")))).sort((t,n)=>ia(t)-ia(n))}function yC(e){return Array.from(new Set(Hc(e).map(t=>{let n=pe(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 vC(e,t){return Array.from(new Set(Hc(e).map(n=>oe(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function vg(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),s=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,i,s,a,c,m,u].some(k=>k!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=Oe(o.toLowerCase(),Dd,"event recurrence frequency"),_=hg(i,"recur_interval",r),h=hg(s,"recur_count",r),y=hC(a,t,n),g=gC(c),v=yC(m),b=vC(u,n);return{freq:f,interval:_,count:h,until:y,by_weekday:g.length>0?g:void 0,by_month_day:v.length>0?v:void 0,exdates:b.length>0?b: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]="e2e87672-508a-5aef-b728-42e40544cf3c")}catch{}})();function Ur(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Gr(e,t,n=Dt()){for(let r of t??[])try{Kd(e,r.id,r.kind,n)}catch(o){throw new l(En(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function wg(e,t){return(await ie(e,{schema:t})).document.metadata.created_at}async function wC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:wg(n,t.schema)}function bC(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 kC(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 wg(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await wC(o,e.context);if(i!==void 0)for(let s of t){let a=r.get(s.id),c=Date.parse(i),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw bC({holder:o,dependency:s,sourceCreatedAt:i,targetCreatedAt:a,registry:e.registry})}}}async function un(e){let t=e.registry??Dt(),n=(e.dependencies??[]).filter(s=>!Hu(s.source_kind)),r=[...new Set(n.map(s=>s.id))],o=await Promise.all(r.map(async s=>({target:s,located:await q(e.pmRoot,s,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:s})=>s===null).map(({target:s})=>s).sort((s,a)=>s<a?-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 kC({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(s=>`dependency_target_unresolved:${s}`)}(function(){try{var e=typeof window<"u"?window:typeof 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 SC={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 EC(e){return SC[e]}function Vc(e){return EC(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]="7bbd7a9a-052b-506d-8d63-6ae512556bde")}catch{}})();var bg="--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.",AC="--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).",TC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,CC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Sg=1e3,Wc=60*Sg,IC=60*Wc;function kg(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 RC(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=TC.exec(r);if(i){let c=i[1]==="-"?-1:1,m=Number.parseInt(i[2],10)*c;return kg(n.getTime()+m*Wc,r)}let s=CC.exec(r);if(s){let[,c,m,u,p]=s;if(m||u||p){let _=c==="-"?-1:1,h=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),g=Number.parseInt(p??"0",10),v=h*IC+y*Wc+g*Sg;return kg(n.getTime()+_*v,r)}}let a=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return oe(a,n,"event.duration")}function Eg(e,t,n,r){if(t&&n)throw new l(AC,d.USAGE);if(n){let i=RC(e,n);if(i<e)throw new l(bg,d.USAGE);return i===e?void 0:i}if(!t)return;let o=oe(t,r,"event.end");if(o<e)throw new l(bg,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]="dfce9924-8453-5ded-a5df-47477caa9fe7")}catch{}})();var OC=["at","date","text","title"],xC=["start","date","end","duration","title","description","location","timezone","all_day",...yg],PC=["key","value"];function Ag(e,t){return t==="trimmed"?e?.trim():e}function NC(e,t){return t==="defined"?e!==void 0:!!e}function us(e,t,n){return e.map(r=>{let o=le(r,"--reminder");He(o,"--reminder",OC);let i=Ag(o.at??o.date,n.valueMode),s=Ag(o.text??o.title,n.valueMode);if(!i||!s)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let a=s.trim();if(!a)throw new l("--reminder text must not be empty",d.USAGE);return{at:oe(i,t,"reminder.at"),text:a}})}function ps(e,t,n){return e.map(r=>{let o=le(r,"--event");He(o,"--event",xC);let i=(o.start??o.date)?.trim();if(!i)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let s=oe(i,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=Eg(s,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,h=u?.trim(),y=p?.trim(),g=f?.trim(),v=_?.trim(),b=[["title",u,h],["description",p,y],["location",f,g],["timezone",_,v]];for(let[L,$,K]of b)if($!==void 0&&!K)throw new l(`--event ${L} must not be empty`,d.USAGE);let k=o.all_day?.trim(),T=vg(o,s,t,n.recurrenceEmptyNumericGuard),O=NC(k,n.allDayEmptyGuard)?gg(k,"--event all_day"):void 0;return{start_at:s,end_at:m,title:h,description:y,location:g,all_day:O,timezone:v,recurrence:T}})}function fs(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(`
20
- `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=le(r,"--type-option");He(a,"--type-option",PC),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,m).trim(),i=r.slice(m+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]="ad3f992c-db2e-5276-a8ae-5d5d4ec8ae68")}catch{}})();var LC=["strict","progressive"],$C=["lightweight"],Rg=new Set(["Reminder","Meeting","Event"]),FC=new Set(["author","created_at","text"]),Jc=[..._g,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...ls],MC=(()=>{let e=new Map;for(let t of Jc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),_s=new Map(Jc.map(e=>[e.optionKey,e.canonical])),DC=Jc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function UC(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 GC(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 Yc(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 jC=Ji();function Og(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};Ve(t.template)&&(t.template=void 0);let r=new Set([..._s.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Ve(i))continue;let s=o==="rank"?"order":_s.get(o)??o;n(s),t[o]=void 0}return Ce(e,Qi(t,jC))}function ve(e){if(e!==void 0)return e}function qC(e,t){return ds({raw:e,supportedFields:DC,resolveDefinition:n=>MC.get(n)??ms(n,"create",t)})}var Tg=["id","kind","type","author","created_at","source_kind"],hs=["path","scope","note"];function KC(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let s=i.trim(),a=gs(s,Tg);Ur(s,a);let c=a?le(i,"--dep"):{id:s,kind:"related"};a&&He(c,"--dep",Tg);let m=ve(c.id),u=zC(ve(c.kind??c.type));if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(m.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(ve(c.source_kind)),f=ve(c.author);return{id:kr(m,n,p),kind:Oe(u,Vt,"dependency kind","kind"),created_at:Yc(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function zC(e){return typeof e=="string"?co(e)??e.trim():e}function gs(e,t){return si(e,t)?!0:li(e)}function fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Re(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(s=>{let a=s.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=le(s,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!FC.has(f)).length>0)return{created_at:Yc(m.created_at,n),author:ve(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Yc(m.created_at,n),author:ve(m.author)??r,text:p}}),explicitEmpty:!1})}function Xc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=gs(r,hs);qa(r,"--file","file path",o);let i=o?le(n,"--file"):{path:r};if(o&&He(i,"--file",hs),!i.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:i.path,scope:Oe(i.scope??"project",at,"file scope"),note:ve(i.note)}}),explicitEmpty:!1})}function Qc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=gs(r,wt);qa(r,"--test","test command",o);let i=o?Zi(le(n,"--test"),"--test"):{command:r},s=ve(i.command),a=ve(i.path);if(!s)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let c=ve(i.timeout_seconds),m=ve(i.timeout);if(c&&m&&c!==m)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let u=c??m;return{command:s,path:a,scope:Oe(i.scope??"project",at,"test scope"),timeout_seconds:u?pe(u,"timeout_seconds"):void 0,pm_context_mode:os(i.pm_context_mode,"--test"),workspace_context_mode:dn(i.workspace_context_mode,"--test"),env_set:Mr(i.env_set,"--test"),env_clear:Dr(i.env_clear,"--test"),shared_host_safe:rs(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:mn(i.assert_stdout_contains),assert_stdout_regex:Hn(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:mn(i.assert_stderr_contains),assert_stderr_regex:Hn(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:is(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:ss(i.assert_json_field_equals,"--test"),assert_json_field_gte:as(i.assert_json_field_gte,"--test"),note:ve(i.note)}}),explicitEmpty:!1})}function Zc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=gs(r,hs),i=o?le(n,"--doc"):{path:r};if(o&&He(i,"--doc",hs),!i.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:i.path,scope:Oe(i.scope??"project",at,"doc scope"),note:ve(i.note)}}),explicitEmpty:!1})}function BC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--reminder","Use --clear-reminders to clear reminders."),{values:us(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function HC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--event","Use --clear-events to clear linked events."),{values:ps(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function VC(e,t,n,r=[]){let o=[...io.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 WC(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Cg(e,t,n){let r=rr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function YC(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 xg(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 JC(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Cg(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Cg(r,e.name,"required_create_repeatables"));return n}function XC(e,t,n,r){for(let o of e)if(!(!xg(t,o)&&!n.has(o)))throw new l(`Option ${Ee("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function QC(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Vc(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Ee("create",i)))].sort((i,s)=>i.localeCompare(s));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function ZC(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:fs(e),explicitEmpty:!1})}async function eI(e){return await di(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 tI(e){return ft(e)?await eI(e):e}function nI(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: ${LC.join(", ")}`,d.USAGE)}function rI(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: ${$C.join(", ")}`,d.USAGE)}function oI(e,t,n){let r=nI(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 iI(e,t,n,r){let o=e.name,i=YC(t),s=JC(e,n),a=An(e,"create",s);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);XC(a.disabled,i,r,o),QC(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Vc(u)?!0:xg(i,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>Ee("create",u)))].sort((u,p)=>u.localeCompare(p))}var Pg=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function sI(e,t){let n=[];for(let r of e){let o=r.match(Pg);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function aI(e,t){return e.filter(n=>{let r=n.match(Pg);return!r||r[2]!==t})}function cI(e,t,n,r){let o=aI(e,t);if(o.length===0)return;let i=Ng(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 lI(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function dI(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function Ng(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"],s=[...new Set([...i,...t])],a=new Set(["--title","--description","--type"]);for(let c of s)a.has(c)||(o.push(...dI(c,e.name,r)),a.add(c));for(let c of n){let m=lI(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function el(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 mI(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 uI(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function pI(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||uI(t.command)==="templates show"):!1}function fI(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(s=>typeof s=="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 _I(e,t,n){if(!pI())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Vo({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 fI(r.result,e)}function H(e,t,n){return e.has(t)||n===void 0?void 0:ve(n)}function pn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var hI=new Set(["milestone","meeting","reminder","event"]);function Lg(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,s=r!==void 0&&r.length>0;return hI.has(e.toLowerCase())&&!o&&!i&&!s}function gI(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`),Lg(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 yI(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Zo(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function vI(e,t,n,r,o,i){let s=wi(fi(o),t.id_prefix);if(Jo(s))return{parent:s,warnings:[]};if(hi(r,s,t.id_prefix),await q(e,s,t.id_prefix,t.item_format,n.type_to_folder))return{parent:s,warnings:[]};let c=qe(s,t.id_prefix);return{parent:s,warnings:_i(c,i).warnings}}async function wI(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await vI(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function bI(e){if(e.explicitId===void 0)return gr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||Dp(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=qe(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 Ig(e,t,n,r,o){let i=H(e,t,n);if(i===void 0)return{value:void 0,warnings:[]};let s=gi(r,i,o);return{value:s.value,warnings:s.warnings}}async function kI(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:s,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(i===void 0)return{dependencyValues:u,status:s};let p=qe(i,n.id_prefix),f=await q(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:s};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:s};let h=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??o.open_status;return{dependencyValues:u,status:h}}function SI(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&be(o,n)){e.type=o;return}be("Task",n)&&(e.type="Task")}function EI(e,t){return e.options.filter(n=>rr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function AI(e,t,n,r,o){let i=e,s=[];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 y=await _I(h,t,n);i=Og(mI(y,i))}if(i.type===void 0&&SI(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=be(i.type,o);if(!a){let h=Gp(i.type),y=h?be(h,o):void 0;if(y)s.push(`type_coercion:${i.type.trim()}:${y}`),i.type=y,a=y;else throw new l(Ot(i.type,o.types,xt(n,r.schema)),d.USAGE)}let c=lo(a,o);if(!c)throw new l(`Invalid type value "${i.type}"`,d.USAGE);let m=c.name,u=EI(c,i),p=u.map(h=>`${h.key}=${String(i[h.key])}`);if(p.length>0){i.typeOption=[...p,...i.typeOption??[]];for(let h of u)delete i[h.key]}let f=rI(i.schedulePreset);if(f!==void 0&&!Rg.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=oI(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:s}}function TI(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 CI(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=_s.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ee("create",r)}`,d.USAGE)}}function II(e){let t=(n,r)=>{let o=_s.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Xi(n,Ee("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 RI(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 OI={"--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 xI(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:s,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let y=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${y}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),u=[Ng(n,r,o,i),...m.map(h=>h.example)].join(" "),p=[`Run "pm create --help --type ${s}" 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 '+s+").")];a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Rg.has(s)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let y=h.split(" ",1)[0],g=OI[y];return g?[g]:[]}))];f.length>0&&p.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 "${s}"`:`Missing required options ${t.join(", ")} for type "${s}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${s}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${s} ${h} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function PI(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?Nt(t.tags):[];return Nn(n,t.addTags)}function NI(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=pn(e,"order",n,o=>pe(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function LI(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 s=e!==t.close_status?void 0:r.completedAt===void 0?i:oe(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:s,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:Uc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:s,warnings:[]}}async function $I(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:s,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=lt(t,n,r,o.item_format,i.type_to_folder),g=Qe(t,r),v=Dt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(L=>v.resolve(L.kind)?.hierarchy),k=await Bi({pmRoot:t,author:s,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,O=[];try{let L=await Ae(t,r,o.locks.ttl_seconds,s,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let $=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await fe(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0;if(await q(t,r,o.id_prefix,o.item_format,i.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if($){let re=F(o.schema);bi($,[...$,c.metadata],r,ze=>ne(ze,re),v)}let Y=await vr({pmRoot:t,settings:o,operation:"create",author:s,before:null,after:c});await Ho({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:yi({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let z=await Ft(t,s,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),me=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await jn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await te(y,Be(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let re=Le({nowIso:f,author:s,op:"create",before:m,after:c,message:u,context:Y.decisions.length===0?void 0:{workflow_policies:Y.decisions}});await Pt(g,re)}catch(re){throw await Sn(y),re}T&&(await k(),T=!1),me=await Mt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await z()}O=[...Y.warnings,...$?Li($,[...$,c.metadata],r):[],...me,...await J({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await J({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],Cn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Qt(c.metadata,p),changed_fields:p})}finally{await L()}}finally{T&&await k()}return O}async function jt(e,t){let n=Og(await tI(e)),r=E(process.cwd(),t.path);await I(r);let o=await A(r),i=F(o.schema),s=Ze(o.schema),a=x(o,R()),c=await AI(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=qC(n.unset,s),{explicitUnsets:_,clearOptionKeys:h}=TI(n,f);CI(n,f),II(n);let y=iI(m,n,p,h),g=S(),v=C(ve(n.author),o.author_default),b=KC(n.dep,g,o.id_prefix,v),k=fn("--comment",n.comment,g,v),T=fn("--note",n.note,g,v),O=fn("--learning",n.learning,g,v),L=Xc(n.file),$=Qc(n.test);$.values=await Kn($.values,v,g);let K=Zc(n.doc),Y=BC(n.reminder,g),z=HC(n.event,g),me=ZC(n.typeOption),re=or(u,me.values,a),ze=R(),j=Tt(ze),ce=so(n.field,ze),Je=mp(n,s,u),tr=new Set(Je.missing_required_flags),Ws=s.definitions.filter(W=>tr.has(`--${W.cli_flag}`));RI(ce,Je,f);let nr=sI(re.errors,u),Bt=nr.map(W=>`--type-option ${W}=<value>`),wd=[...new Set([...y,...Bt,...Je.missing_required_flags])].sort((W,ra)=>W.localeCompare(ra));xI({combinedMissingFlags:wd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:nr,openStatus:i.open_status,type:u,createMode:p,missingRequiredRuntimeFields:Ws}),cI(re.errors,u,m,i);let Ne=await bI({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),St=n.status!==void 0?UC(n.status,i):GC(m,i),Ys=n.priority!==void 0?$n(n.priority):2,P=f.metadataKeys,je=PI(P,n),st=pn(P,"deadline",n.deadline,W=>oe(W,new Date(g),"deadline")),Qr=pn(P,"estimated_minutes",n.estimatedMinutes,W=>Ln(W,"estimated-minutes")),Et=H(P,"acceptance_criteria",n.acceptanceCriteria),Js=H(P,"definition_of_ready",n.definitionOfReady),Xe=NI(P,n),Xs=H(P,"goal",n.goal),Zr=H(P,"objective",n.objective),tb=H(P,"value",n.value),nb=H(P,"impact",n.impact),rb=H(P,"outcome",n.outcome),ob=H(P,"why_now",n.whyNow),ib=H(P,"assignee",n.assignee),sb=P.has("author")?void 0:ve(n.author)??v,ab=H(P,"parent",n.parent),bd=await yI(ab,n,P,r),Qs=bd.parent,cb=bd.parentSource,lb=H(P,"reviewer",n.reviewer),db=pn(P,"risk",n.risk,W=>Oe(Hi(W),bn,"risk")),mb=pn(P,"confidence",n.confidence,W=>Wi(W)),ub=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,kd=o.validation.sprint_release_format,Ht=[...c.warnings,...gI(u,Ne,st,Y.values,z.values)],Sd=await wI({itemId:Ne,parent:Qs,pmRoot:r,settings:o,typeRegistry:a,policy:ub});Qs=Sd.parent,Ht.push(...Sd.warnings);let Ed=Ig(P,"sprint",n.sprint,"sprint",kd),pb=Ed.value;Ht.push(...Ed.warnings);let Ad=Ig(P,"release",n.release,"release",kd),fb=Ad.value;Ht.push(...Ad.warnings);let Td=H(P,"blocked_by",n.blockedBy),Cd=await kI({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:i,blockedBy:Td,dependencyValues:b.values,status:St,statusExplicit:n.status!==void 0,nowValue:g,author:v}),Zs=Cd.dependencyValues;Gr(Ne,Zs),Ht.push(...await un({pmRoot:r,dependencies:Zs,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ne,createdAt:g}],schema:o.schema})),St=Cd.status;let _b=H(P,"blocked_reason",n.blockedReason),hb=H(P,"unblock_note",n.unblockNote),gb=H(P,"reporter",n.reporter),yb=pn(P,"severity",n.severity,W=>Oe(Vi(W),kn,"severity")),vb=H(P,"environment",n.environment),wb=H(P,"repro_steps",n.reproSteps),Id=H(P,"resolution",n.resolution),bb=H(P,"expected_result",n.expectedResult),kb=H(P,"actual_result",n.actualResult),Sb=H(P,"affected_version",n.affectedVersion),Eb=H(P,"fixed_version",n.fixedVersion),Ab=H(P,"component",n.component),Tb=pn(P,"regression",n.regression,W=>Yi(W)),Cb=H(P,"customer_impact",n.customerImpact),ea=el(n.title,"--title"),ta=n.description??"",eo=n.body??"",Rd=await jn({title:ea,description:ta,body:eo},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Ht.push(...Ti(Rd));let na=LI(St,i,o,n,Id,g),Ib=na.closeReason,Rb=St===i.close_status?g:void 0,Ob=na.completedAt;Ht.push(...na.warnings);let to=Fa({id:Ne,title:ea,description:ta,type:u,type_options:re.normalized,status:St,closed_at:Rb,completed_at:Ob,close_reason:Ib,priority:Ys,tags:je,created_at:g,updated_at:g,deadline:st,assignee:ib,author:sb,estimated_minutes:Qr,acceptance_criteria:Et,definition_of_ready:Js,order:Xe,goal:Xs,objective:Zr,value:tb,impact:nb,outcome:rb,why_now:ob,parent:Qs,reviewer:lb,risk:db,confidence:mb,sprint:pb,release:fb,blocked_by:Td,blocked_reason:_b,unblock_note:hb,reporter:gb,severity:yb,environment:vb,repro_steps:wb,resolution:Id,expected_result:bb,actual_result:kb,affected_version:Sb,fixed_version:Eb,component:Ab,regression:Tb,customer_impact:Cb,dependencies:Zs,comments:k.values,notes:T.values,learnings:O.values,files:L.values,tests:$.values,docs:K.values,reminders:Y.values,events:z.values,...ce,...Je.values});try{ao(to,ze)}catch(W){throw new l(W instanceof Error?W.message:"Invalid extension item field values",d.USAGE)}let xb=et({metadata:to,body:eo},{schema:o.schema,extensionFieldNames:j}),Pb={metadata:{},body:""},Od=[..._].sort((W,ra)=>W.localeCompare(ra)),Nb=WC(n.message,Od),xd=VC(to,eo,Od,[...Object.keys(ce),...Object.keys(Je.values??{})]),Lb=await $I({pmRoot:r,type:u,id:Ne,settings:o,typeRegistry:a,author:v,extensionFieldNames:j,afterDocument:xb,beforeDocument:Pb,historyMessage:Nb,changedFields:xd,nowValue:g,similarityCandidate:{title:ea,description:ta,body:eo},allowDuplicate:n.allowDuplicate}),Pd=structuredClone(to);p==="strict"&&_.has("dependencies")&&(Pd.dependencies=[]);let $b=dg(Ne,u,St,i);return Lg(u,st,Y.values,z.values)&&Bu(`[pm] warning: ${u} '${Ne}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ne} --deadline <ISO>' or 'pm update ${Ne} --event "start=<ISO>,end=<ISO>"'.`),{item:Pd,changed_fields:xd,warnings:[...Ht,...Lb],...Object.fromEntries([["parent_source",cb],["next_transition",$b],["similarity_advisory",Rd]].filter(W=>W[1]!==void 0))}}import ys 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]="eef2ba25-bbdb-5c06-9f90-1cf485e98497")}catch{}})();async function tl(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),s=await Vp({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),a=s.targetPath?ys.relative(r,s.targetPath).split(ys.sep).join("/"):void 0;return{item:s.item,changed_fields:s.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:s.item.status,...a?{target_path:a}:{},history_retained:ys.relative(r,Qe(r,s.item.id)).split(ys.sep).join("/"),tombstone_retention:"retain_append_only",warnings:s.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]="8023e71b-f733-572c-bdc0-e9b8f481232c")}catch{}})();async function FI(e){await I(e)}async function nl(e,t,n){let r=E(process.cwd(),n.path);if(await FI(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),f=xn(C(void 0,p.author_default));return await dp(r),await $i({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Zo(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 f=await MI(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let i=await A(r),s=x(i,R()),a=await q(r,e,i.id_prefix,i.item_format,s.type_to_folder);if(!a)throw await _t(r,e,i.id_prefix,s.type_to_folder);let c=qe(a.id,i.id_prefix),m=await ie(a,{schema:i.schema}),u=$g(m.document.metadata.title);return await lp(r,c),await $i({pmRoot:r,settings:i,principal:xn(C(void 0,i.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function MI(e,t){let n=await A(e),r=x(n,R()),o=await q(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await ie(o,{schema:n.schema});return $g(i.document.metadata.title)}function $g(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 vs(e){return Ko("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]="80ec599f-7198-5b07-bca2-253f85c137b7")}catch{}})();var sl=[...zc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Bc,...ls],DI=(()=>{let e=new Map;for(let t of sl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ws=new Map(sl.map(e=>[e.optionKey,e.canonical])),UI=sl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),GI=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),jI=Ji({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Kg(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([...ws.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!Ve(i))continue;let s=o==="rank"?"order":ws.get(o)??o;n(s),t[o]=void 0}return Ce(e,Qi(t,jI))}function zg(e,t,n=[]){return ds({raw:e,supportedFields:UI,resolveDefinition:r=>{let o=n.find(s=>{let a=s.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return DI.get(r)??ms(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var Fg=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 Mg(e){let t=e.disallowedFlags.flatMap(r=>{let o=Fg.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=Fg.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 qI(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,u)=>{c&&u.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 Mg({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 s=[];i(t.status!==void 0,"--status",s),i(t.closeReason!==void 0,"--close-reason",s),i(t.assignee!==void 0,"--assignee",s),i(t.parent!==void 0,"--parent",s),i(t.blockedBy!==void 0,"--blocked-by",s),i(t.blockedReason!==void 0,"--blocked-reason",s),i(t.unblockNote!==void 0,"--unblock-note",s),i(t.dep!==void 0,"--dep",s),i(t.depRemove!==void 0,"--dep-remove",s),i(t.replaceDeps===!0,"--replace-deps",s),i(t.replaceTests===!0,"--replace-tests",s),i(t.replaceFiles===!0,"--replace-files",s),i(t.replaceDocs===!0,"--replace-docs",s),i(t.note!==void 0,"--note",s),i(t.learning!==void 0,"--learning",s),i(t.test!==void 0,"--test",s),i(t.reminder!==void 0,"--reminder",s),i(t.event!==void 0,"--event",s),i(t.clearDeps===!0,"--clear-deps",s),i(t.clearComments===!0,"--clear-comments",s),i(t.clearNotes===!0,"--clear-notes",s),i(t.clearLearnings===!0,"--clear-learnings",s),i(t.clearFiles===!0,"--clear-files",s),i(t.clearTests===!0,"--clear-tests",s),i(t.clearDocs===!0,"--clear-docs",s),i(t.clearReminders===!0,"--clear-reminders",s),i(t.clearEvents===!0,"--clear-events",s);let a=[...n].filter(c=>GI.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(s.push(...a),s.length>0)throw Mg({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: ${s.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:s})}function KI(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 zI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=ku({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: ${Su(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function BI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Bg(e)}function Bg(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 Vn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var HI=["id","kind","type","author","created_at","source_kind"],VI=["id","kind","type","author","created_at","source_kind"];function Hg(e){return e.startsWith("```")||e.includes(`
21
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:li(e)}function Vg(e){return typeof e=="string"?co(e)??e.trim():e}function ks(e,t,n,r){return e?(Re(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let s=i.trim(),a=Hg(s);Ur(s,a);let c=a?le(i,"--dep"):{id:s,kind:"related"};a&&He(c,"--dep",HI);let m=c.id?.trim(),u=Vg((c.kind??c.type)?.trim());if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(m.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(Vn(c.source_kind)),f=Vn(c.author);return{id:kr(m,t,p),kind:Oe(u,Vt,"dependency kind","kind"),created_at:BI(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function WI(e,t){return e?(Re(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=Hg(r);if(Ur(r,o,"--dep-remove"),o){let i=le(r,"--dep-remove");He(i,"--dep-remove",VI);let s=i.id?.trim();if(!s)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(s.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${s}"`,d.USAGE);let a=Vg(Vn(i.kind??i.type)),c=br(Vn(i.source_kind)),m=Vn(i.author),u=Vn(i.created_at);return{id:kr(s,t,c),kind:a?Oe(a,Vt,"dependency kind","kind"):void 0,source_kind:c,author:m,created_at:u?Bg(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:qe(r,t)}})):[]}function bs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function YI(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 JI(e,t,n,r){let o=[...e??[]],i=!1;if(t===void 0){let s=o.filter(a=>a.kind!=="blocked_by");return s.length!==o.length&&(o=s,i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(s=>s.kind==="blocked_by"&&s.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 XI(e,t,n,r,o,i){if(e===void 0||t)return{};let s=e.trim();if(s.length===0)return{};let a=await q(n,qe(s,r),r,o,i);return a?{id:a.id}:{unresolved:s}}function QI(e,t,n,r,o){let i=JI(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 ZI(e){return`${e.path}::${e.scope}`}function eR(e){return`${e.path}::${e.scope}`}function tR(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Wg(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 Dg(e,t){let n=rr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function nR(e,t,n){let r=new Set,o=(i,s)=>{s&&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 s of i.optionKeys)o(s,!0)}return r}function rR(e,t,n,r,o){let i=lo(e,n);if(!i)throw new l(`Invalid type value "${e}"`,d.USAGE);let s=An(i,"update",[]);if(s.errors.length>0)throw new l(s.errors.join("; "),d.CONFLICT);let a=nR(t,r,o);for(let c of s.disabled)if(a.has(Dg(c,e)))throw new l(`Option ${Ee("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of s.required)if(!a.has(Dg(c,e)))throw new l(`Missing required option ${Ee("update",c)} for type "${e}"`,d.USAGE)}var oR=new Set(["order","rank"]),iR=pa.filter(e=>!oR.has(e)),Yg=["tags","closeReason",...iR],sR=["title","description","body","status","closeReason","completedAt","priority","type",...pa,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],aR=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>oe(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Ln(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"}],cR=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Oe(Hi(e),bn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Wi(e)}],lR=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Oe(Vi(e),kn,"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=>Yi(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function il(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(`${Ee("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 dR(e){return Kg(await di(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 al(e){return ft(e)?await dR(e):Kg(e)}function mR(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 rl(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 cl(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);rl({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),rl({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),rl({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function uR(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 pR(e){let t={};for(let n of Yg)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function fR(e,t){let n=pR(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=ws.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ee("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 _R(e){let t=(n,r)=>{let o=ws.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Xi(n,Ee("update",r),i)};for(let n of Yg)t(e[n],String(n));t(e.order??e.rank,"order"),Re(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Re(e.event,"--event","Use --clear-events to clear linked events.")}function hR(e,t){let n={};for(let r of sR)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.runtimeFields=Object.keys(t).length>0,n}async function gR(e){let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ie(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function yR(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function vR(e){e.before&&bi(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>ne(t,e.statusRegistry),Dt())}function wR(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 bR(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=wi(fi(e.options.parent),e.settings.id_prefix);if(Jo(t))return{resolvedParentValue:t,warnings:[]};if(hi(e.id,t,e.settings.id_prefix),await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=qe(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:_i(r,e.parentReferencePolicy).warnings}}function kR(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function SR(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ie(t,{schema:e.settings.schema}),r=e.options.type!==void 0?be(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=zI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function ER(e){if(!e.fieldFlags.status||ee(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=Ce(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await ot(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let i=await vt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),s=[...e.workflowTransitionWarnings,...r,...i.warnings,"auto_routed_from_update_to_close"];return{item:i.item,changed_fields:[...o,...i.changed_fields],warnings:s}}function AR(e,t,n,r){return t.title!==void 0&&(e.metadata.title=el(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 TR=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function CR(e,t){for(let n of TR)e[n]!==void 0&&(delete e[n],t.push(n))}function IR(e,t,n,r,o){let i=KI(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}!ne(i,t.statusRegistry)&&ne(r,t.statusRegistry)&&CR(e.metadata,o)}function RR(e,t,n,r){if(t.options.status!==void 0&&IR(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!ne(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=oe(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function OR(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&&ne(n,t.statusRegistry)&&!ne(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function xR(e,t,n,r){RR(e,t,n,r),OR(e,t,n,r)}function PR(e,t,n){let r=be(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=$n(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=be(t.options.type,t.typeRegistry);if(!o)throw new l(Ot(t.options.type,t.typeRegistry.types,xt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return rR(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),NR(e,t,r,n),r}function NR(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=fs(t.options.typeOption??[]),s=or(n,i,t.typeRegistry);if(s.errors.length>0)throw new l(s.errors.join("; "),d.USAGE);e.metadata.type_options=s.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=or(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function LR(e,t){let n=new Set(t.map(o=>bs(o))),r=new Set;return e.filter(o=>{if(!n.has(bs(o)))return!0;let i=YI(o);return r.has(i)?!1:(r.add(i),!0)})}function $R(e,t,n){let r=t.filter(o=>!e.some(i=>Wg(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 FR(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=LR(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>bs(i)));for(let i of t.dependencyUpdates.additions){let s=bs(i);o.has(s)||(r.push(i),o.add(s))}}t.dependencyRemovals.length>0&&($R(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>Wg(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function MR(e,t,n){ol(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),ol(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),ol(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function ol(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 DR(e,t,n){Ug(e,"files",t.options.file,t.fileUpdates.values,ZI,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),UR(e,t,n),Ug(e,"docs",t.options.doc,t.docUpdates.values,eR,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Ug(e,t,n,r,o,i,s,a){if(!(n===void 0&&!s.has(t))){if(i)e.metadata[t]=r;else if(s.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function UR(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Gg(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Gg([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Gg(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=tR(r);n.has(o)||(t.push(r),n.add(o))}return t}function GR(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 s=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Nt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=ci(Nn(s,r),o),n.changedFields.push("tags")}il(aR,t.options,n),qR(e,t,n.changedFields)}function jR(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=ai(Pn(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 s=i.criteria.join("; ");e.metadata.acceptance_criteria!==s&&(s===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=s,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function qR(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=pe(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function KR(e,t,n,r){zR(e,t,n.changedFields),BR(e,t,n.changedFields),il(cR,t.options,n),jg(e,t,"sprint",r,n.changedFields),jg(e,t,"release",r,n.changedFields),HR(e,t,n.changedFields),il(lR,t.options,n)}function zR(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 BR(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=gi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function HR(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)&&QI(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function VR(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=us(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=ps(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function WR(e,t,n){qg(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),qg(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let s=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??s;throw new l(`Cannot combine --unset ${s} with --${c}`,d.USAGE)}dt(e[o],i)||(e[o]=i,n.push(o))}let r=so(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))dt(e[o],i)||(e[o]=i,n.push(o))}function qg(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function YR(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],i=[],s=AR(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};xR(e,t,s,o),PR(e,t,o),FR(e,t,o),MR(e,t,o),DR(e,t,o),GR(e,t,c),jR(e,t,c),KR(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"))&&Gr(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")),VR(e,t,o),WR(a,t,o);try{ao(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new l(p instanceof Error?p.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,u=[...new Set(o)].filter(p=>p==="body"?e.body!==r:!dt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${Pn(n.acceptance_criteria).length}:${Pn(m.acceptance_criteria).length}`),{changedFields:u,warnings:i}}async function Jg(e,t,n,r={}){t=await al(t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=F(i.schema),a=Ze(i.schema),c=R(),m=Tt(c),u=x(i,c),p=i.governance.workflow_enforcement??"off",f=p==="off"?[]:bu(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,a,m),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);cl(t),uR({definitions:mR(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),qI(e,t,g),fR(t,h),_R(t);let v=C(t.author,i.author_default),b=new Date,k=b.toISOString(),T=ks(t.dep,i.id_prefix,k,v);Gr(e,T.additions);let O=await un({pmRoot:o,dependencies:T.additions,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:i.schema}),L=WI(t.depRemove,i.id_prefix),$=fn("--comment",t.comment,k,v),K=t.ownershipMetadataBypass===!0&&$.values?{...$,values:$.values.map(je=>({...je,author:v}))}:$,Y=fn("--note",t.note,k,v),z=fn("--learning",t.learning,k,v),me=Xc(t.file),re=Qc(t.test);re.values=await Kn(re.values,v,k);let ze=Zc(t.doc),j=[],ce=await bR({id:e,options:t,unsetTargets:h,pmRoot:o,settings:i,typeRegistry:u,parentReferencePolicy:_}),Je=await XI(t.blockedBy,g.has("blocked_by"),o,i.id_prefix,i.item_format,u.type_to_folder),tr=Je.id,Ws=[...ce.warnings,...kR(Je)],nr=ti(t,a,t.runtimeFieldCommands),Bt=hR(t,nr);if(!Object.values(Bt).some(Boolean))return gR({pmRoot:o,id:e,settings:i,typeRegistry:u});j.push(...await SR({options:t,fieldFlags:Bt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:s,typeRegistry:u,pmRoot:o,id:e,settings:i}));let Ne=await ER({options:t,fieldFlags:Bt,statusRegistry:s,workflowTransitionWarnings:j,global:n,id:e});if(Ne)return Ne;wR(t);let St=Dt(),Ys=Bt.parent&&!g.has("parent")||T.additions.some(je=>St.resolve(je.kind)?.hierarchy),P=await Bi({pmRoot:o,author:v,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:Ys});try{let je=await yR({fieldFlags:Bt,clearedMetadataKeys:g,pmRoot:o,settings:i,typeToFolder:u.type_to_folder}),st,Qr,Et=await Hp({pmRoot:o,settings:i,typeToFolder:u.type_to_folder,id:e,op:JR(t,r),author:v,message:t.message,resolveHistoryContext:()=>Qr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Xe){st=XR({document:Xe,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:s}),Qr=st?{recurrence:st}:void 0,je=je?.map(Zr=>Zr.id===Xe.metadata.id?structuredClone(Xe.metadata):Zr);let Xs=YR(Xe,{options:t,settings:i,typeRegistry:u,statusRegistry:s,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:g,dependencyUpdates:T,dependencyRemovals:L,commentUpdates:K,noteUpdates:Y,learningUpdates:z,fileUpdates:me,testUpdates:re,docUpdates:ze,resolvedParentValue:ce.resolvedParentValue,resolvedBlockedByDependencyId:tr,runtimeFieldUpdates:nr,nowValue:b,nowIso:k,author:v,pmRoot:o});return vR({before:je,document:Xe,statusRegistry:s}),Xs}});await P();let Js=je?Li(je,je.map(Xe=>Xe.id===Et.item.id?Et.item:Xe),Et.item.id):[];return{item:Et.item,changed_fields:Et.changedFields,warnings:[...j,...Ws,...O,...Js,...Et.warnings],...st===void 0?{}:{lifecycle_transition:st}}}finally{await P()}}function JR(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function XR(e){if(e.recurrenceReason===void 0)return;let t=ee(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!ne(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(s=>{let a=o[s];return typeof a=="string"?[[s,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function ot(e,t,n){return Jg(e,t,n)}async function Xg(e,t,n,r){let o=await Jg(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]="cd0e532e-0f27-5786-8216-c17132f6e784")}catch{}})();async function ll(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),s=F((await A(i)).schema),a=s.open_status,c=vs(s),m=n.status??a,u=ee(m,s)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} 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([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await Xg(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.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]="f366dd76-73b4-55c4-8c63-2913d0a0c380")}catch{}})();async function Qg(e,t,n){return[...await Promise.resolve().then(()=>vp(Qe(e,t),t)).catch(()=>[])].reverse().find(i=>i.patch.some(s=>s.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]="f2901314-4044-5a91-ad72-6b4bebde16c2")}catch{}})();var Zg="no_available_next_item";function ey(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function jr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=F(i.schema),a=C(r.author,i.author_default),c=xn(a),m=null,u=!1,p=[],f=await se({pmRoot:o,settings:i,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,hu(_.metadata.status,s)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let T=await Qg(o,_.metadata.id,y);throw new l(`Item ${_.metadata.id} is already ${T}. 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."]})}p.push(`claim_takeover:${m}->${a}`)}let b={assignee:a,claim_principal:c},k=["assignee","claim_principal"].filter(T=>_.metadata[T]!==b[T]);return Object.assign(_.metadata,b),{changedFields:k,warnings:p}}});return u||await dc({pmRoot:o,settings:i,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function ty(e,t,n={},r={}){let o=QR(n.maxAttempts),i=await A(E(process.cwd(),t.path)),s={...n,author:C(n.author,i.author_default)},a=await Rr({...r,callerAuthor:s.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return ZR(c.slice(0,o),e,t,s)}function QR(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 ZR(e,t,n,r={},o=jr){let i=0;for(let a of e){i+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:i,available:!0};if(!c.skipped)return m}catch(c){if(!ey(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:[Zg]};let s=i===0;throw new l(s?"No actionable items matched the selection filters":"No actionable item remained available to claim",s?d.NOT_FOUND:d.CONFLICT,{code:Zg,why:s?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[s?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function qr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=C(r.author,i.author_default),a=xn(s),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await se({pmRoot:o,settings:i,id:e,op:"release",author:s,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){Lr(_,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await mc({pmRoot:o,principal:a,itemId:u.item.id});let p=F(i.schema),f=$a(u.item.status,p)===$a(p.in_progress_status,p);return{item:u.item,released_by:s,changed_fields:u.changedFields,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${u.item.id} remains ${u.item.status} and unclaimed. If work is paused, run pm release ${u.item.id} --pause to move it to ${p.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]="7f0e8f0f-bef3-5d61-b851-7582a03430b6")}catch{}})();async function dl(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 ml(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start requires an explicit item id and cannot be combined with --next or --if-available",d.USAGE);let r=await A(E(process.cwd(),n.path)),o=vs(F(r.schema)),i=await jr(e,t.force===!0,n,t),s=await dl(e,"claim",()=>ot(e,Ut(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:e,action:"start_task",claim:i,update:s}}async function ul(e,t,n){let r=await A(E(process.cwd(),n.path)),o=F(r.schema).open_status,i=await ot(e,Ut(t,{status:o},["assignee","pause"]),n),s=await dl(e,"update",()=>qr(e,t.force===!0,n,t));return{id:e,action:"pause_task",update:i,release:s}}async function pl(e,t,n,r){let o=await vt(e,t,n,r),i=await dl(e,"close",()=>qr(e,n.force===!0,r,n));return{id:e,action:"close_task",close:o,release:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="31407e14-880c-5637-a2d5-3569e575e729")}catch{}})();async function ny(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(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 s=e.args.next===!0||r.next===!0?await ty(o,e.global,i,i):await jr(Kr(e,r),o,e.global,i);return Se(s,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Kr(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function fl(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function ry(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return r.releaseAssignment===!0?_n(e,"close_task"):Se(await vt(Kr(e,r),fl(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function _n(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=_e(e.args,e.options),i=Kr(e,o),s=Ut(o,{force:e.force===!0||o.force===!0}),a=t==="start_task"?await ml(i,s,e.global):t==="pause_task"?await ul(i,s,e.global):await pl(i,fl(e,o),s,e.global);return Se(a,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function oy(e){if(e.options.pause===!0)return _n(e,"pause_task");let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=await qr(Kr(e,r),e.force===!0,e.global,r);return Se(o,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function iy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await ll(Kr(e,r),fl(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]="fc60339e-561c-5ac3-bdb3-116bd55e35b5")}catch{}})();function Ss(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 ${Fu(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]="d9a4fa9f-2f70-5ce9-b9c0-24e58b120420")}catch{}})();var e0=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],sy=["brief","standard","deep"],ly="plan-step-",wl="draft",vl=["bug-investigation","feature-implementation","refactoring-sprint"],ay={"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 t0(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(ay,t)?ay[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${vl.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${vl[0]}`]});return n.map(r=>({...r}))}function n0(e,t){return t>0?Math.round(e/t*100):0}function dy(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function Ke(e){return Array.isArray(e)?e.flatMap(t=>Dn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Dn(e,{unique:!1}):[]}function xe(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function my(e,t=wl){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=sa.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${sa.join(", ")}`,d.USAGE);return r}function bl(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=aa.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${aa.join(", ")}`,d.USAGE);return r}function uy(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=la.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${la.join(", ")}`,d.USAGE);return r}function r0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=ca.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${ca.join(", ")}`,d.USAGE);return n}function o0(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=sy.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${sy.join(", ")}`,d.USAGE);return n}function i0(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 _l=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function s0(e,t){let n=e,r={},o=[];for(let i of t){let s=i.startsWith("plan.")?i.slice(5):i;if(s.length!==0){if(!_l.has(s)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[..._l].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[..._l].join(",")}`}});return r}function kl(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 Sl(e){let t=kl(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 El(e){let t=kl(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 Al(e){let t=kl(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 a0(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=n0(t.completed,t.total),t}function c0(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${ly}${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 Wn(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(s=>s.order===o);if(i)return i}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function cy(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 l0(e,t){let n=t.filter(s=>s.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 s of e.slice().sort((a,c)=>a.order-c.order)){let a=cy(s);if(a){o.push({from_step:s.id,...a});continue}r.push(s)}return{targets:r,skipped:o}}let i=new Set;for(let s of t){let a=Wn(e,s);if(i.has(a.id))continue;i.add(a.id);let c=cy(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function d0(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 m0(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function u0(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function De(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((s,a)=>s.order-a.order),r=a0(n),o=m0(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??wl,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:u0(n),linked_items:(e.dependencies??[]).map(s=>({id:s.id,kind:s.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function Ue(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!Ha(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function py(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 p0(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function fy(e,t){let n=x(e.settings,R()),r=await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let o=await ie(r,{schema:e.settings.schema});return py(o.document.metadata),{document:o.document,itemId:r.id}}function f0(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Ke(e.related))t.push(`id=${n},kind=related`);for(let n of Ke(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Ke(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function _0(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 h0(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Ke(e.dependsOn).length>0||Ke(e.link).length>0}function g0(e){let t=e.stepTitle?.trim()||void 0,n=dy(e.step),r=e.template?.trim()?t0(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function y0(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 ${vl[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 v0(e,t){let n=bl(e.stepStatus,"pending"),r=Tl(e,"depends_on"),o=xe(e.file).map(Sl),i=xe(e.test).map(El),s=xe(e.doc).map(Al),a=S();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:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function w0(e){let t=g0(e),n=h0(e);if(y0(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[v0(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((o,i)=>({id:`${ly}${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 _y(e,t,n=[]){Ce(e,t),n.length>0&&Lp(t,n)}async function b0(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=my(e.mode,wl),i=r0(e.harness),s=e.fromSearch?.trim(),a=_0(e),{steps:c,hasPerStepDetailOptions:m}=w0(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 u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:xe(e.file),test:xe(e.test),doc:xe(e.doc),field:xe(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:f0(e),message:e.message??(s?`plan create (search: ${s})`:"plan create")};_y(e,f);let _=await jt(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(g){let v=["plan_mode"];g.metadata.plan_mode=o,i&&(g.metadata.plan_harness=i,v.push("plan_harness"));let b=e.scope?.trim();b&&(g.metadata.plan_scope=b,v.push("plan_scope"));let k=e.resumeContext?.trim();return k&&(g.metadata.plan_resume_context=k,v.push("plan_resume_context")),g.metadata.plan_steps=c,v.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],v.push("plan_validation")),p&&(g.metadata.assignee=p,v.push("assignee")),{changedFields:v}}}),y=De(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ue(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function k0(e,t,n){let r=o0(t.depth),o=i0(t.fields),{document:i,itemId:s}=await fy(n,e),a=De(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:s0(a,o),next_actions:Ue(s,a),warnings:[],generated_at:S()}}function S0(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 it(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){py(o.metadata);let i=F(e.ctx.settings.schema);if(ne(o.metadata.status,i)||Ha(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 s=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(s,o);n=c.resultStep;let m=s.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=S0(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function E0(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=bl(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:s,resultStep:a,itemId:c}=await it({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;hy(u,void 0,o,i);let f=A0(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=De(s.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ue(c,m),warnings:[],generated_at:S()}}function hy(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 A0(e,t,n){let r=Tl(t,"depends_on"),o=xe(t.file).map(Sl),i=xe(t.test).map(El),s=xe(t.doc).map(Al),a=S();return{id:c0(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:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Tl(e,t){let n=Ke(e.dependsOn).map(u=>({id:u,kind:t})),r=Ke(e.related).map(u=>({id:u,kind:"related"})),o=Ke(e.blocks).map(u=>({id:u,kind:"blocks"})),i=Ke(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),s=Ke(e.link),a=uy(e.linkKind,t),c=e.linkNote?.trim(),m=s.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...i,...m]}async function hl(e,t,n,r){let{document:o,resultStep:i,itemId:s}=await it({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Wn(c,r.stepRef),p=S(),f=r.finalStatus??bl(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return hy(c,u.status==="in_progress"?u.id:void 0,f,_),T0(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=De(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:i,next_actions:Ue(s,a),warnings:[],generated_at:S()}}function T0(e,t,n,r){C0(e,t,n),I0(e,t),e.status=n,e.updated_at=r,R0(e,n,r)}function C0(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 I0(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=xe(t.file).map(Sl),o=xe(t.test).map(El),i=xe(t.doc).map(Al);r.length>0&&(e.files=gl(e.files,r)),o.length>0&&(e.tests=gl(e.tests,o)),i.length>0&&(e.docs=gl(e.docs,i))}function gl(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 R0(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function O0(e,t,n,r,o){let{document:i,itemId:s,resultStep:a}=await it({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(m){let u=Wn(m,r),p=m.filter(_=>_.id!==u.id),f=Math.max(1,Math.min(o,p.length+1));return p.splice(f-1,0,u),p.forEach((_,h)=>{_.order=h+1,_.updated_at=S()}),m.length=0,m.push(...p),{changedSteps:[u.id],resultStep:u}}}),c=De(i.metadata,"standard");return{action:"reorder-step",plan:c,step:a,next_actions:Ue(s,c),warnings:[],generated_at:S()}}async function x0(e,t,n,r){let{document:o,itemId:i,resultStep:s}=await it({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let m=Wn(c,r),u=c.filter(p=>p.id!==m.id);return u.forEach((p,f)=>{p.order=f+1}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=De(o.metadata,"standard");return{action:"remove-step",plan:a,step:s,next_actions:Ue(i,a),warnings:[],generated_at:S()}}async function P0(e,t,n,r){let o=Tl(t,uy(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:s,itemId:a,resultStep:c}=await it({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Wn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of o){let v=h(g);y.has(v)||(_.push(g),y.add(v))}if(f.linked_items=_,f.updated_at=S(),i){let g=p.metadata.dependencies??[],v=k=>`${k.kind}:${k.id}`,b=new Set(g.map(v));for(let k of o){let T=k.kind==="depends_on"?"blocked_by":k.kind,O={id:k.id,kind:T,created_at:S(),author:C(t.author,n.settings.author_default)};b.has(v(O))||(g.push(O),b.add(v(O)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=De(s.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ue(a,m),warnings:[],generated_at:S()}}async function N0(e,t,n,r){let o=Ke(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:i,itemId:s,resultStep:a}=await it({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Wn(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=De(i.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ue(s,c),warnings:[],generated_at:S()}}async function yl(e,t,n,r){let o=d0(r,t);if(!o){let m=`--${r}-text`,u=`--${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> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let i=C(t.author,n.settings.author_default),{document:s,itemId:a}=await it({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=S();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:i,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=De(s.metadata,"deep");return{action:r,plan:c,next_actions:Ue(a,c),warnings:[],generated_at:S()}}async function L0(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 it({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),s=De(o.metadata,"brief");return{action:"resume",plan:s,next_actions:Ue(i,s),warnings:[],generated_at:S()}}async function $0(e,t,n){let r=my(t.mode??"approved","approved"),{document:o,itemId:i}=await it({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),s=De(o.metadata,"brief");return{action:"approve",plan:s,next_actions:Ue(i,s),warnings:[],generated_at:S()}}function gy(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function F0(e,t){let n=De(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ue(e.itemId,n),warnings:gy(t),generated_at:S()}}function M0(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 D0(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of xe(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let c=s.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let[m,...u]=c,p=`${m}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new l(`Invalid --field entry "${o}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}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:M0(e.parent,e.planItemId,o)};_y(e.options,i,["description",...Object.keys(n)]);let s=await jt(i,{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:o.id})}return t}function U0(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let i=e.find(a=>a.id===r.id);if(!i)continue;let s=i.linked_items??[];s.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=s,i.updated_at=S()}}async function G0(e,t,n){let r=Ke(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,R()),s=be(o,i);if(!s)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await fy(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=l0(u,r);if(p.length===0){if(f.length>0)return F0(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await D0({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:s,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await it({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(v){return U0(v,p,_),{changedSteps:p.map(b=>b.id)}}}),g=De(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ue(y,g),warnings:gy(f),generated_at:S()}}function j0(e){if(e.subcommand==="create")return e;let t=dy(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:Ce(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 q0(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 K0={create:(e,t)=>b0(e.options,e.global,t),show:(e,t)=>k0(bt(e,"show"),e.options,t),"add-step":(e,t)=>E0(bt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=hn(e,"update-step");return hl(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=hn(e,"complete-step");return hl(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 hl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=q0(e);return O0(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=hn(e,"remove-step");return x0(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=hn(e,"link");return P0(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=hn(e,"unlink");return N0(n.id,e.options,t,n.stepRef)},decision:(e,t)=>yl(bt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>yl(bt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>yl(bt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>L0(bt(e,"resume"),e.options,t),approve:(e,t)=>$0(bt(e,"approve"),e.options,t),materialize:(e,t)=>G0(bt(e,"materialize"),e.options,t)};function z0(e){let t=K0[e];if(!t)throw Te({command_path:"plan",token:e,allowed:e0});return t}async function yy(e){let t=await p0(e.global),n=j0(e),r=await z0(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Ss(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]="3ef785ae-bb1e-59dd-993c-3be56ddc26c2")}catch{}})();var wy=1,Il="update-many",B0=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),H0=["--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(", "),V0={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"},W0=[{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"}],Y0={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"},by=e=>{let t={};for(let[n,r]of Object.entries(e))B0.has(n)||r!==void 0&&(t[n]=r);return t},J0=e=>Object.keys(by(e)).length>0,ky=e=>typeof e=="string"?e.trim():e,X0=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Cl=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},Q0=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??ky(e)},Z0={priority:X0,estimatedMinutes:Cl,order:Cl,rank:Cl,regression:Q0},eO=(e,t)=>{if(t!==void 0)return(Z0[e]??ky)(t)},tO=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return Y0[t]??t},Es=(e,t)=>dt(e,t),nO=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],rO=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,oO=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",vy=(e,t)=>t===void 0?void 0:e[t],Yn=e=>Array.isArray(e)?e.length:0,iO=(e,t,n)=>{let r=n[e.addKey],o=vy(n,e.removeKey),i=Yn(r),s=Yn(o),a=n[e.clearKey]===!0,c=vy(n,e.replaceKey)===!0;if(![a,c,i>0,s>0].includes(!0))return;let m=nO(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:oO({replace:c,clear:a,removeCount:s}),clear:a,replace:c,add_count:i,remove_count:s,before_count:rO(e.field,m)}}},sO=(e,t)=>{let n=[];for(let r of W0){let o=iO(r,e,t);o!==void 0&&n.push(o)}return n},aO=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],cO=(e,t)=>{if(![t.tags!==void 0,Yn(t.addTags)>0,Yn(t.removeTags)>0].includes(!0))return;let n=aO(e.tags),r=t.tags===void 0?n:Nt(t.tags),o=Nn(r,t.addTags),i=ci(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),s=n.slice().sort((a,c)=>a.localeCompare(c));if(!Es(s,i))return{field:"tags",before:n,after:i}},lO=(e,t)=>{let n=e.acceptance_criteria,r=ai(Pn(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(!Es(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},dO=(e,t,n)=>{for(let[r,o]of Object.entries(V0)){let i=n[r];if(i===void 0)continue;let s=t[o],a=eO(r,i);Es(s,a)||e.push({field:o,before:s,after:a})}},mO=(e,t,n,r)=>{let o=ti(n,r,["update_many"]);for(let[i,s]of Object.entries(o)){let a=t[i];Es(a,s)||e.push({field:i,before:a,after:s})}},uO=(e,t,n)=>{for(let r of n??[]){let o=tO(r),i=t[o];i!==void 0&&e.push({field:o,before:i,after:null})}},pO=(e,t,n={})=>{let r=e,o=[],i=cO(r,n);if(i&&o.push(i),dO(o,r,n),Yn(n.addAc)>0||Yn(n.removeAc)>0){let s=lO(r,n);s!==void 0&&o.push(s)}return o.push(...sO(r,n)),mO(o,r,n,t),uO(o,r,n.unset),{id:e.id,changes:o}},fO=(e,t)=>Up(e,t,{strict:!0,flagLabel:"--filter-status"}),_O=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)},hO=[({update:e})=>{e.priority!==void 0&&$n(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,R());if(!be(e.type,r))throw new l(Ot(e.type,r.types,xt(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&&oe(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&Ln(e.estimatedMinutes,"estimated-minutes")}],gO=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of hO)i(o)},yO=async e=>{let t=await oi(e.pmRoot,Il,e.rollbackId,wy),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await ii(t.items,(o,i)=>sn(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}},vO=async e=>{let t={schema_version:wy,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 ri(e.pmRoot,Il,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},wO=(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))},Rl=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},bO=async e=>{let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:F(n.schema),runtimeFieldRegistry:Ze(n.schema)}},kO=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Ir(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return yO({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},SO=async e=>{fO(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=pO(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:wO(e.options.list?.ids,r)}},EO=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:[],...Rl(e)}),AO=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:[],...Rl(e)}),TO=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 s=Ka({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await ot(i.id,s,e.global);t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(s){t.push({id:i.id,status:"failed",error:En(s)})}}return{rows:t,updatedIds:n}},CO=async e=>{if(e.plan.actionable.length===0)return AO(e.plan);let t=S(),n=ni(Il,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),i=e.options.checkpoint===!1?void 0:await vO({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}),s=await TO({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>s.rows.filter(f=>f.status===p).length,c=a("updated"),m=a("skipped"),u=a("failed");return{...en({applied:c,skipped:m,failed:u,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:u,rows:s.rows,ids:s.updatedIds,...Rl(e.plan)}},Sy=async(e,t)=>{let n=await bO(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Ka(await al(e.update))});let o=by(e.update);if(_O(e.list),r!==void 0)return kO({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!J0(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${H0}), or pass --dry-run for a filter-only preview.`,d.USAGE);gO(e.update,n.settings,n.statusRegistry,n.pmRoot),cl(e.update);let i=await un({pmRoot:n.pmRoot,dependencies:ks(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),s=await SO({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:i});return await un({pmRoot:n.pmRoot,dependencies:ks(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:s.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?EO(s):CO({runtime:n,options:e,global:t,plan:s})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4e85b9bc-3387-5fb8-ac8b-c8f115c82b60")}catch{}})();function IO(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 RO(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 OO(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 Ey(e,t,n){let r=IO(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),s=[t.since,t.eventType].some(h=>h!==void 0),a=OO(t.since),c=yr(t.limit),m=await Bn(e,{...t,...s?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,s].includes(!0)},n,{input:await Ki(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>zn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:RO(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."]}}),u=t.eventType?.trim(),p=m.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),v=[!u,h.event_type===u].includes(!0);return[!s,[y,g,v].every(Boolean)].includes(!0)}),f=s?Tc(p,c):p,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...s?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}import KO from"node:path";import xO from"node:fs/promises";import Ay 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]="ff76c0f3-d8cf-51de-a7e6-acb0a4942268")}catch{}})();var PO="templates",NO=".json",LO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,$O=Xo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),FO=new Set($O);function MO(e){let t=e.trim();if(!LO.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 Ty(e){return Ay.join(e,PO)}function Cy(e,t){return Ay.join(Ty(e),`${t}${NO}`)}async function DO(e){await I(e)}function Iy(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function UO(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(FO.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 Iy(t)}function GO(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 s=o.trim();if(s.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof i=="string"){r[s]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[s]=[...i];continue}throw new l(`Template "${t}" contains invalid value for option "${s}".`,d.GENERIC_FAILURE)}return Iy(r)}function jO(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=GO(r.options,t),i=S();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 qO(e,t){let n=await Z(Cy(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return jO(n,t)}async function Ol(e,t,n){let r=E(process.cwd(),n.path);await DO(r);let o=MO(e),i=UO(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let s=S(),a=Cy(r,o),c=s;await G(a)&&(c=(await qO(r,o)).created_at);let m={name:o,created_at:c,updated_at:s,options:i},u=await A(r);return await xO.mkdir(Ty(r),{recursive:!0}),await nt({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
22
- `,op:"templates:save",author:C(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,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]="5529deea-21db-509b-9562-d5e08dfc004a")}catch{}})();var Py=["list","show","apply","lint"],zO="schema-types",BO="schema-statuses",HO="schema-fields";function As(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Ny(){let{profiles:e,warnings:t}=pu(As());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:yu(n.definition)})),warnings:t,generated_at:S()}}function Ly(e){let t;try{t=jo(e,As())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...vu(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function $y(e){let t;try{t=jo(e,As())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=Wu(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:S()}}function VO(e,t){return KO.join(e,"templates",`${t}.json`)}async function WO(e,t){let n=await Z(VO(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 Ry(e,t,n,r){let o=new Map;for(let i of r.templates){let s=await WO(e,i.name);s!==void 0&&o.set(i.name,s)}return{typesRaw:await Z(ut(e,t.files.types,mt.types)),statusesRaw:await Z(ut(e,t.files.statuses,mt.statuses)),fieldsRaw:await Z(ut(e,t.files.fields,mt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Jn(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 Oy(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Jn(t.types.changes),statuses:Jn(t.statuses.changes),fields:Jn(t.fields.changes),workflows:Jn(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Jn(t.config.changes),templates:Jn(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,s)=>i.localeCompare(s)),generated_at:S()}}async function YO(e){await I(e)}function JO(e){try{let t=jo(e,As());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Fy(e,t,n){let r=E(process.cwd(),n.path);await YO(r);let o=JO(e),i=o.profile,s=o.warnings,a=t.dryRun===!0,c=await A(r),m=qo(c.schema);if(a){let v=await Ry(r,m,c,i),b=xy(i,v);return Oy(i,b,!1,!0,[...s])}let u=C(t.author,c.author_default),p=xp(c),f=!!t.force,_=[...s],h=[],y=async v=>{h.push(await Ae(r,v,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(zO),await y(BO),await y(HO);let v=await Ry(r,m,c,i);if(g=xy(i,v),g.types.changed){let b=ut(r,m.files.types,mt.types);await nt({pmRoot:r,filePath:b,raw:Go(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(i.types.map(O=>au(O).name)),T=g.types.file.definitions.filter(O=>k.has(O.name));await gf(r,T,_,"profile:apply-type-folder"),_.push(...await J({path:b,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let b=ut(r,m.files.statuses,mt.statuses);await nt({pmRoot:r,filePath:b,raw:gu(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await J({path:b,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let b=ut(r,m.files.fields,mt.fields);await nt({pmRoot:r,filePath:b,raw:fu(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await J({path:b,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let b of g.config.changes){if(b.status==="unchanged")continue;let k=zo(b.key);k!==void 0&&Bo(c,k,b.value)}c.schema.type_workflows=g.workflows.result,await $e(r,c,"profile:apply-config")}for(let b of g.templates.changes)b.status!=="unchanged"&&await Ol(b.name,{...b.options},n)}finally{for(let v of h.reverse())try{await v()}catch{}}return Oy(i,g,g.changed,!1,_)}function xy(e,t){try{return Yu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import rx from"node:fs/promises";import Nl 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]="451970e8-8403-5527-b795-a873241c015e")}catch{}})();var Dy=10,gn="https://schema.unbrained.dev/pm/eval-query-set/v1";var Ts={schema:gn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},We=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},XO=new Set(["keyword","semantic","hybrid"]);function My(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 QO(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=My(r,n),i=Array.from({length:t.size},()=>1),s=My(i,n);return s===0?0:o/s}function ZO(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 xl(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 ex(e,t,n){return n<=0?0:xl(e,t,n)/n}function tx(e,t,n){return t.size===0?0:xl(e,t,n)/t.size}function Uy(e,t,n){return{ndcg:QO(e,t,n),mrr:ZO(e,t,n),precision:ex(e,t,n),recall:tx(e,t,n),relevant_total:t.size,retrieved_relevant:xl(e,t,n)}}function Gy(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 nx(e,t){if(typeof e!="object"||e===null)throw new We(`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 We(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new We(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new We(`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 We(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!XO.has(n.mode)))throw new We(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:O_(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Pl(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==gn)throw new We(`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 We('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new We("Eval query set must contain at least one query");return{schema:gn,queries:n.map((r,o)=>nx(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]="d4020969-4ce5-5f87-ae41-f5a3dec0a197")}catch{}})();var ox=Nl.join("search","eval-queries.json"),Ll={schema:gn,examples:[JSON.stringify(Ts)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},ix=new Set(["keyword","semantic","hybrid"]),sx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!ix.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},ax=e=>{if(e===void 0||e==="")return Dy;let t=Bd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},cx=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},qt=e=>Math.round(e*1e4)/1e4,lx=async e=>{try{return await rx.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ll,examples:[`echo '${JSON.stringify(Ts)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},dx=(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,Ll)}},mx=e=>{try{return Pl(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ll)}},ux=async e=>mx(dx(await lx(e),e)),px=async(e,t,n,r)=>{let o=e.mode??t,s=(await Or(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=Uy(s,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:x_(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:qt(a.ndcg),mrr:qt(a.mrr),precision:qt(a.precision),recall:qt(a.recall)}}},fx=(e,t,n,r)=>{let o=Gy(n);return{k:e,query_count:t.length,aggregate:{ndcg:qt(o.ndcg),mrr:qt(o.mrr),precision:qt(o.precision),recall:qt(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=ax(e.k),o=sx(e.mode),i=cx(e.failUnder),s=e.queries?Nl.resolve(process.cwd(),e.queries):Nl.join(n,ox),a=await ux(s),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await px(u,o,r,t);m.push(f),c.push(p)}return fx(r,c,m,i)};import{readFile as _x,writeFile as hx}from"node:fs/promises";import gx 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]="47487ad3-22a0-52ac-8a42-ebaca439cb6e")}catch{}})();var qy=["item","history","relationship","json"];function yx(e){let t=e.trim().toLowerCase();if(qy.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${qy.join(", ")}.`,d.USAGE)}function vx(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 $l(e,t){try{return await _x(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function wx(e){let t=E(process.cwd(),e.path);return await G(ue(t))?A(t):null}function bx(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Ky(e,t){let n=yx(e.artifact),r=vx(e.prefer),o=gx.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([$l(e.basePath,"base"),$l(e.oursPath,"ours"),$l(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=Wf(i,s,a);c=_.merged,p.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 _=Yf(i,s,a);c=_.merged,p.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 wx(t),h=bx(e.itemPath??o,_),y=Tt(R()),g=Jf(i,s,a,{format:h,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=g.merged,u.push(...g.conflict_fields),p.item={fields_from_theirs:g.fields_from_theirs,union_fields:g.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let v=gp(c,{format:h,schema:_?.schema,extensionFieldNames:y}),b=v.metadata,k=[...new Set([...g.fields_from_theirs,...g.union_fields,...g.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:g.fields_from_theirs,unionFields:g.union_fields,mergedFieldHashes:Object.fromEntries(k.map(T=>[T,Vf(T==="body"?v.body:b[T])])),decisions:g.conflict_decisions,operation:await Qf(process.cwd(),e.itemPath)}}}else{let _=Xf(i,s,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await hx(o,c,"utf8"),m!==void 0){let _=await e_(m);_!==null&&(p.receipt=nn(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.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"&&p.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:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5fd3624a-d36b-58e6-8053-f2c0626e0c10")}catch{}})();async function zy(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Zf(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Gt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Gt(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 Ii(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as kx}from"node:fs/promises";import Sx 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]="017ec565-4b8d-5da3-badc-e9f4ca3ec433")}catch{}})();var Ex=4;function By(e){let t=e.checks.find(a=>a.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,s=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:s}}async function Ax(e,t){let n=[];for(let r of t){let o;try{o=await kx(Sx.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 s;try{s=JSON.parse(i)}catch{continue}let a=i_(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!o_(a)||a.eventTimestamp===void 0||Yo(a.eventTimestamp,r_)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function Tx(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 Gt(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 Cx(e){try{return{status:"fulfilled",value:await Gt(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 Ix(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 Rx(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=>Ii(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}async function Hy(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=By(o),s=await Ax(r,i.coordinates),a=await ki(r),c=a??r,m=await t_(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 u=await Tx({candidates:s,options:e,global:t}),p=m.receipts,f=await zy({cwd:a,receipts:p,dryRun:n,author:e.author,message:e.message,global:t}),_=new Set(f),h=new Map;for(let j of p.filter(ce=>!_.has(ce.id))){let ce=h.get(j.item_id)??[];ce.push(j),h.set(j.item_id,ce)}let y=Object.fromEntries([...h].map(([j,ce])=>[j,{merge:{receipts:ce.map(nn)}}])),g=Object.fromEntries([...h].map(([j,ce])=>[j,{gitWorkspaceRoot:a,receipts:ce}])),v=await Oi({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:y,...p.length>0?{mergeReceiptProofById:g}:{}},t),b=new Set(v.streams.map(j=>j.id)),k=[...h.keys()].filter(j=>!b.has(j)),T=await Rf(k,Ex,j=>Cx({id:j,dryRun:n,options:e,global:t,auditContext:y[j],mergeReceiptProof:g[j]}));Ix({receiptOnlyIds:k,results:T,repair:v});let O=await Rx({dryRun:n,pendingReceipts:p,repair:v,receiptWorkspaceRoot:c}),L=await Ni({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),$=u===0?o:await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),K=By($),Y=L.checks.every(j=>j.status==="ok"),z=n?p.length===0:O+f.length===p.length,me=[v.totals.failed===0,Y,z,K.count===0,!K.truncated].every(Boolean),re=i.truncated||K.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,ze=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",re,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:me?["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.",re,...s.length>0&&u===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(j=>j!==void 0);return{ok:me,dry_run:n,repair:v,receipts:{pending_before:p.length,reconciled:O,abandoned:f.length,summaries:p.map(nn),missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:u,missing_history_references_after:K.count},validation:L,guidance:ze,generated_at:L.generated_at}}import{createHash as Ox}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]="117a463a-c0ab-569f-92e9-e85d14a1cf91")}catch{}})();var Yy=1,Jy=/^[A-Za-z0-9_-]+$/,xx=100,Vy=1e3;var nB=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Ye(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 Px(e){return Ox("sha256").update(Yt({type:Ye(e.type),author:Ye(e.author),item:Ye(e.item),harness:Ye(e.harness),agent_instance:Ye(e.agentInstance),provenance:Ye(e.provenanceFilter)})).digest("hex").slice(0,24)}function Wy(e,t){let n={version:Yy,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 Nx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Yy,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 Lx(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Jy.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(!Nx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function $x(e){let t=e??xx;if(!Number.isSafeInteger(t)||t<0||t>Vy)throw new l(`Mutation event limit must be an integer from 0 to ${Vy}.`,d.USAGE,{code:"invalid_event_limit"});return t}function Fx(e,t){let n=e?.trim();if(!n)return{};if(Jy.test(n))return{cursor:Lx(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 Mx(e,t){let n=await Ma(e,t);if(n===null){if(!await wp(e))return{...await bp(e,t),source:"authoritative_history"};n=await Ma(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 Dx(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 Cs(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=$x(e.limit),r=Dx(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,s=S_(o.agent_identity.harness_signals),a=E_({provenance:e.provenanceFilter},s),c=Ye(e.harness),m=Px(e),{cursor:u,sinceTimestamp:p}=Fx(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:Ye(e.type),authors:Ye(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:Ye(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:Ye(e.item),limit:n},_=await Mx(t,f),h=_.events.map(y=>({...r==="row"?{cursor:Wy(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:A_(y.entry,i,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:Wy(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:T_(_.events.map(y=>y.entry),i,s)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a196ae-61e1-528d-99a2-83eb9e11158b")}catch{}})();var Ux="1h",Gx="now",jx="+1d";function Kt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Xy(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 Ce(n,r)}async function Qy(e,t,n,r){let o=Xy(e,t,n),i=[];return Kt(i,"start",n.start??Gx),n.end!==void 0?Kt(i,"end",n.end):Kt(i,"duration",n.duration??Ux),Kt(i,"location",n.location),Kt(i,"timezone",n.timezone),n.allDay===!0&&Kt(i,"all_day","true"),o.event=[i.join(",")],jt(o,r)}function Zy(e,t,n){return Qy("Meeting",e,t,n)}function ev(e,t,n){return Qy("Event",e,t,n)}function tv(e,t,n){let r=Xy("Reminder",e,t),o=[];return Kt(o,"at",t.at??jx),Kt(o,"text",t.text??e),r.reminder=[o.join(",")],jt(r,n)}import Br from"node:crypto";import{cp as nv,lstat as qx,mkdir as yn,readFile as Xn,readdir as Ml,rename as iv,rm as Ul,writeFile as Is}from"node:fs/promises";import M 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]="91604cb2-8afd-585e-9c18-26e223df25bc")}catch{}})();var sv="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var av=M.join("runtime","workspace-snapshots"),Kx=new Set(["checkpoints","locks","runtime","search","transactions"]),zx=/^[a-z0-9][a-z0-9._-]*$/,zr="sdk-workspace-transaction",Fl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},cv={renameEntry:iv,removeEntry:async e=>{await Ul(e,{recursive:!0,force:!0})}},Dl=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 Xn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==zr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await te(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
23
- `)}};async function lv(e,t=""){let n=await Ml(M.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,s)=>i.name.localeCompare(s.name))){if(t.length===0&&Kx.has(o.name))continue;let i=M.posix.join(t.replaceAll(M.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await lv(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function dv(e){let t=await lv(e),n=Br.createHash("sha256"),r=[],o=0;for(let s of t){let a=await Xn(M.join(e,s));r.push(a),o+=a.byteLength,n.update(s),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let i=n.digest("hex");return{manifest:{schema:sv,fingerprint:i,files:t,bytes:o},contents:r}}function rv(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
24
- `).filter(t=>t.trim().length>0).length}async function Bx(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 s=>[s,await Xn(M.join(e,s))]));for(let[s,a]of i)n.set(s,a)}return n}function Gl(e){if(!zx.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 mv(e,t){return ir(`workspace_snapshot_${e}`,t,{codes:{capacity:Fl.capacity.code,permission:Fl.permission.code,resource:Fl.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 vn(e){return M.join(e,av)}function uv(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 pv(e,t){try{return JSON.parse(await Xn(e,"utf8"))}catch(n){throw Ct(n)?uv(t):n}}async function ov(e,t,n){try{await Ul(e,{recursive:n})}catch(r){throw Ct(r)?uv(t):r}}async function Hx(e,t,n=cv){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 Vx(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 Wx(e,t){return Gl(t),/^[a-f0-9]{64}$/.test(t)?t:(await pv(M.join(vn(e),"refs",`${t}.json`),t)).fingerprint}async function jl(e,t={}){if(t.name!==void 0&&(Gl(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 dv(e),o=vn(e),i=M.join(o,"objects",n.fingerprint),s=!1;try{s=(await qx(i)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&Ct(a)))throw a}if(!s){let a=M.join(o,"objects",`.create-${process.pid}-${Br.randomUUID()}`);await mv("create_object",async()=>{await yn(M.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=M.join(a,"files",m);await yn(M.dirname(u),{recursive:!0}),await Is(u,r[c])}await Is(M.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
25
- `,"utf8"),await yn(M.dirname(i),{recursive:!0})}),s=await Hx(a,i)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=M.join(o,"refs");await yn(c,{recursive:!0});let m=M.join(c,`.ref-${process.pid}-${Br.randomUUID()}`);await Is(m,`${JSON.stringify(a,null,2)}
26
- `,"utf8"),await iv(m,M.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:s}}async function Hr(e,t){let n=await Wx(e,t),r=await pv(M.join(vn(e),"objects",n,"manifest.json"),t);if(r.schema!==sv||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function ql(e){let t=vn(e),n=await Ml(M.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&Ct(o))return[];throw o}),r=await Ml(M.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&Ct(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Hr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Xn(M.join(t,"refs",o),"utf8"))))}}async function Kl(e,t){let n=await Hr(e,t),{manifest:r,contents:o}=await dv(e),i=new Map(r.files.map((p,f)=>[p,o[f]])),s=await Bx(M.join(vn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=i.get(p),_=s.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=rv(i.get(p)),_=rv(s.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function fv(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,s=await Ae(e,zr,o,r,!1,!1,i),a=new Dl(mo(e,zr),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Kl(e,t),f=await Hr(e,t),_=await jl(e),h=f.fingerprint,y=vn(e),g=M.join(y,"objects",h,"files"),v=M.dirname(e),b=M.basename(e);c=M.join(v,`.${b}.restore-${Br.randomUUID()}`);let k=M.join(v,`.${b}.backup-${Br.randomUUID()}`);await mv("restore_stage",async()=>{await yn(c,{recursive:!0}),await nv(g,c,{recursive:!0,force:!1}),await yn(M.join(c,"runtime"),{recursive:!0}),await nv(y,M.join(c,av),{recursive:!0,force:!1})});let T=await Rp({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),O=M.relative(c,T.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let L=mo(c,zr);return await yn(M.dirname(L),{recursive:!0}),await Is(L,await Xn(mo(e,zr)),{flag:"wx"}),m=!0,await Vx(c,e,k,cv,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:O,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([Ul(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await s()}}}async function _v(e,t){Gl(t);let n=vn(e);if(!/^[a-f0-9]{64}$/.test(t))return await ov(M.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await ql(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await ov(M.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66cead7f-c3f3-5073-82a5-ad1535f3f611")}catch{}})();function Vr(e){let t={...e.args,...e.options};return Ce(e.options,t)}function kt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Qn(e){return typeof e=="string"?[e]:ge(e)}function hv(e){return jy(Vr(e),e.global)}function gv(e){let t=Vr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Cs({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Qn(t.type),author:Qn(t.author),item:Qn(t.item),limit:t.limit===void 0?void 0:Fe(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Qn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Qn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Qn(t.provenanceFilter)}})}function yv(e){let t=Vr(e),n=kt(t,"subcommand");if(n==="install")return df({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Hy({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return n_({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return Ky({artifact:kt(t,"artifact"),basePath:kt(t,"basePath"),oursPath:kt(t,"oursPath"),theirsPath:kt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Te({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function vv(e){let t=Vr(e),n=kt(t,"subcommand");if(n==="position")return P_(e.global);if(n!=="snapshot")throw Te({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??kt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return jl(o,{name:w(t,"name")});if(r==="list")return ql(o);let i=kt(t,"target");if(r==="inspect")return Hr(o,i);if(r==="delete")return _v(o,i);if(r==="restore")return t.dryRun===!0?Kl(o,i):fv(o,i,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Fe(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Fe(t.lockWaitMs,"lockWaitMs")});throw Te({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Rs(e){let t=Vr(e),n=kt(t,"title");return e.action==="meet"?Zy(n,t,e.global):e.action==="event"?ev(n,t,e.global):tv(n,t,e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="086d2640-2a64-554a-9e40-a8f6994ae3a8")}catch{}})();function wv(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ge(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import xP from"node:fs/promises";import Dv 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]="60090339-2f94-5f22-be47-518498838b92")}catch{}})();function Os(e,t,n,r,o,i="min"){let s=o==="min"?e-t:t-e,a=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return s<0||s===0&&r!==null&&a<0}function Yx(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(Os(f,s,p,o,"min")&&(s=f,o=p),Os(f,a,p,i,"max","max")&&(a=f,i=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function bv(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>Yx(_,h)),i=0,s=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(i+=_.lines,s+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);Os(h,m,_.id,a?.id??null,"min")&&(m=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);Os(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:s,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as Xx}from"node:crypto";import{execFile as Qx}from"node:child_process";import Ev from"node:path";import{promisify as Zx}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39d2b5aa-c6f3-57ac-adb4-e775bc838828")}catch{}})();var kv=1;function Jx(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function zl(e){if(e===null)return{format_version:kv,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==kv||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!Jx(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c800f76b-2867-51f5-80d6-fb7b1c61f9e4")}catch{}})();var eP=Zx(Qx),tP=50,Sv=1e3,nP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Av(e){let t=e.trim().toLowerCase();if(!nP.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function rP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Wr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function oP(e){let t=e??tP;if(!Number.isSafeInteger(t)||t<0||t>Sv)throw new l(`Improvement observation limit must be an integer from 0 to ${Sv}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Tv(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function iP(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Av(n.metric),o=rP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let i=await aP(e,n.revision),s=Wr(n.source,"source"),a=Wr(n.itemId,"itemId"),c=Wr(n.unit,"unit"),m=Wr(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,s??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Tv(n.observedAt??S(),"observedAt"),...i,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...s===void 0?{}:{source:s},...m===void 0?{}:{idempotency_key:m}};return{id:Xx("sha256").update(Yt(u)).digest("hex").slice(0,24),...u}}function sP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function aP(e,t){let n=Wr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await eP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Vd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function cP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Cv(e,t={}){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await iP(n,r,e),i=Ev.join(n,"improvement-ledger.json"),s=await Op({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=zl(a),m=sP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${Yt(c)}
27
- `,result:o})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function Iv(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=e.metric===void 0?void 0:Av(e.metric),r=e.since===void 0?void 0:Tv(e.since,"since"),o=oP(e.limit),s=zl(await Z(Ev.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of s){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...s].reverse().slice(0,o),total:s.length,truncated:s.length>o,trends:[...a].map(([,c])=>cP(c)).sort((c,m)=>c.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e7a7f40-523d-590f-8aea-90b65535506e")}catch{}})();function Rv(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function lP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function dP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Bl(e=pr,t=On){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function mP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Hl(e,t=On,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let s=`${o.agent_harness}\0${i}`,a=r.get(s)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(s,a)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function uP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),s=i.filter(c=>c.entries>=r),a=s.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:s.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:a}}function pP(e){let t=[...e].sort((i,s)=>i.ts.localeCompare(s.ts)||i.author.localeCompare(s.author)||i.op.localeCompare(s.op)||i.before_hash.localeCompare(s.before_hash)||i.after_hash.localeCompare(s.after_hash)),n=new Map,r=new Map;for(let i of t){let s=i.agent_episode,a=Rv(i),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(i);continue}let u={id:a.id,...s?.label===void 0?{}:{label:s.label},...s?.parent_id===void 0?{}:{parent_id:s.parent_id},source:a.source,entries:[i],children:[]};n.set(c,u),s!==void 0&&r.set(a.id,u)}let o=[];for(let i of n.values()){let s=i.parent_id?r.get(i.parent_id):void 0;s&&lP(i,s,r)?s.children.push(i):o.push(i)}return dP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0eeefcd-2202-55c6-94e9-0372fcfe0c87")}catch{}})();var fP=1e4,Ov=1e5,_P=1e3,hP=30,gP=["append","comment","docs","file","learning","note","test_run"];function yP(e){let t=e??fP;if(!Number.isSafeInteger(t)||t<1||t>Ov)throw new l(`History analytics event limit must be an integer from 1 to ${Ov}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function xv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function vP(e){let t=e?.trim();if(!t)return new Date(Date.now()-hP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Pv(e,t){let n=yP(t.eventLimit),r=vP(t.since),o=[],i=r,s=!1;for(;o.length<n;){let a=await Cs({pmRoot:e,since:i,limit:Math.min(_P,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),s=a.has_more,i=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:s,...s?{next_cursor:i}:{},source:"history_event_index"}}}function wP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function bP(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function kP(e){return gP.some(t=>e.startsWith(t))}function Nv(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function SP(e,t,n){let r=new Map,o=new Map,i=new Map;for(let s of t){let a=wP(s.entry,e),c=bP(s.entry),m=o.get(s.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(s.item_id,u),!a)continue;let p=Nv(r,a);p.events+=1,kP(s.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,i.set(s.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:i}}function EP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let s=t.get(i);s&&(Nv(e,s).defectEscapes+=1)}}}function AP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function TP(e,t,n,r,o,i){let{buckets:s,lastCloseValue:a}=SP(e,t,r);return EP(s,a,n),{dimension:e,status:s.size===0?"unavailable":"available",rows:[...s].map(([c,m])=>AP(c,m,o,i)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function CP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function IP(e,t,n){let r=Bl(t),o=Hl(e,On,n),i=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),s=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:i,undeclared:s,warnings:[...i.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...s.map(a=>`provenance_dimension_undeclared:${a}`)]}}function Lv(e,t=pr,n={}){let r=xv(n.minimumSample);return{...IP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function $v(e,t,n,r={}){let o=xv(r.minimumSample),i=CP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(s=>TP(s,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c81415a5-81fa-57ed-936f-236841e5f066")}catch{}})();var RP=32;function OP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Yr(e,t){let n=OP(e).map(o=>{let[i,...s]=o.split(","),a=i.indexOf("="),c=i.slice(0,a).trim(),m=i.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of s){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,i)=>o.name.localeCompare(i.name)).slice(0,RP)}function Fv(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Mv(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,s)=>s.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a567e72a-faff-580d-b9ae-e2ebfa492b89")}catch{}})();function PP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function NP(e,t,n,r,o){let i=wr(e,"type",r),s=new Set(i.rows.map(f=>f.key)),a=t.filter(f=>!s.has(f)),m=(o?[...i.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=PP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function LP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function $P(e){let t=Dv.join(e,"history");if(!await G(t))return[];await In({path:t,scope:"project"});let n=(await xP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=Dv.join(t,o),s=await Z(i);s!==null&&(await In({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:s}))}return r}async function FP(e,t){let n=[],r=S();for(let o of Yr(t.observe,r))n.push(await Cv({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function MP(e,t,n){let r={};return t.byAssignee&&(r.assignee=wr(e,"assignee",n)),t.byTag&&(r.tag=wr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=wr(e,"priority",n)),r}async function DP(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},s=o.provenanceCoverage||o.fleetAttribution?await Pv(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&s?Lv(s,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&s?$v(s,t,r,i):void 0}}function UP(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:S()}}async function Vl(e,t={}){let n=E(process.cwd(),e.path);await I(n);let r=await A(n),o=await FP(e,t),i=x(r,R()),s=F(r.schema),a=t.fieldUtilization?await Bp(n,r.item_format,i.type_to_folder,void 0,r.schema):await fe(n,r.item_format,i.type_to_folder,void 0,r.schema);await Mp({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=vi(s),m=NP(a,i.types,s.definitions.map(k=>k.id),c,t.includeEmpty===!0),u=await $P(n),p=0;for(let k of u)p+=LP(k.raw);let f=t.storage?bv(u):void 0,_=t.metadataCoverage?Zp(a,c):void 0,h=MP(a,t,c),y=t.fieldUtilization?ef(a):void 0,g=t.measurements===!0||o.length>0?await Iv({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:b}=await DP(n,a,r,s.terminal_statuses,t);return UP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:o,provenanceCoverage:v,fleetAttribution:b})}import GP from"node:fs/promises";import zt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bc2412e-9aa0-55ea-bc51-97a6bb9b4763")}catch{}})();var zv=zt.join("runtime","telemetry","events.jsonl"),Bv=zt.join("runtime","telemetry","state.json"),jP=zt.join("runtime","telemetry"),qP=20,Hv=Jt.filter(e=>e.lifecycle==="deprecated"),Uv=["status","flush","stats","clear"],Gv=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Wl=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,jv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},KP=e=>({command:Wl(e.event.command,"<unknown>"),eventType:Wl(e.event.event_type,"unknown"),eventSchemaVersion:jv(e.event.schema_version),clientSchemaVersion:jv(e.client_schema_version)}),zP=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),BP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},HP=e=>{let t=e?.command_resolution;return Wl(t,"")||void 0},Vv=(e,t)=>{e[t]=(e[t]??0)+1},VP=(e,t)=>{let n=BP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=HP(t);r!==void 0&&Vv(e.resolution_counts,r)},WP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,qv=(e,t)=>{t!==void 0&&e.add(t)},YP=(e,t)=>{let n=KP(t),r=e.get(n.command)??zP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,WP(t.attempts)),Vv(r.event_type_counts,n.eventType),qv(r.event_schema_versions,n.eventSchemaVersion),qv(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&VP(r,t.event.payload),e.set(n.command,r)},JP=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,s)=>i-s),o=Object.entries(t.resolution_counts).sort((i,s)=>i[0].localeCompare(s[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,s)=>i[0].localeCompare(s[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,s)=>i-s),client_schema_versions:[...t.client_schema_versions].sort((i,s)=>i-s),...r.length>0?{duration_p50_ms:Gv(r,.5),duration_p95_ms:Gv(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},XP=e=>{let t=(e??"status").trim().toLowerCase();if(Uv.includes(t))return t;throw Te({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Uv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Jl=()=>{throw new l("--limit must be a positive integer",d.USAGE)},Wv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Jl():e,QP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Jl():Wv(Number.parseInt(t,10))},ZP=e=>e===void 0?qP:typeof e=="number"?Wv(e):typeof e=="string"?QP(e):Jl(),eN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},tN=e=>{try{let t=JSON.parse(e);return eN(t)?t:void 0}catch{return}},nN=e=>e===null?[]:e.split(`
28
- `).map(t=>t.trim()).filter(t=>t.length>0),Yv=e=>{let t=nN(e),n=[],r=0;for(let o of t){let i=tN(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},rN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oN=e=>{try{let t=JSON.parse(e);return rN(t)?t:{}}catch{return{}}},Yl=async e=>{let t=await Z(e);return t===null||t.trim().length===0?{}:oN(t)};function iN(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function sN(e,t,n){let r=Object.create(null);for(let[o,i]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof i!="object"||i===null||Array.isArray(i))continue;let s=i;!Number.isSafeInteger(s.count)||s.count<1||typeof s.last_seen!="string"||!s.last_seen.startsWith(o)||(r[o]={count:s.count,last_seen:s.last_seen})}return r}function Kv(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let i of Hv){let s=r[i.alias];if(typeof s!="object"||s===null||Array.isArray(s))continue;let a=s;if(a.canonical!==i.canonical||typeof a.days!="object"||a.days===null||Array.isArray(a.days))continue;let c=sN(a.days,t,o);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function aN(e,t,n){let r=iN(n),o=await Yl(t),i=Kv(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(i))return i;try{await Va(async()=>{let s=await Yl(t);if(s.alias_usage===void 0)return;let a=Kv(s.alias_usage,r);JSON.stringify(s.alias_usage)!==JSON.stringify(a)&&await te(t,`${JSON.stringify({...s,alias_usage:a},null,2)}
29
- `)},e,250)}catch{}return i}var xs=e=>e??null,Ps=async e=>{let t=await A(e),n=zt.join(e,zv),r=zt.join(e,Bv),o=await Z(n),i=Yv(o),s=await Yl(r),a=Wp();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:xs(s.last_attempted_flush_at),last_successful_flush_at:xs(s.last_successful_flush_at),last_failed_flush_at:xs(s.last_failed_flush_at),last_failed_flush_error:xs(s.last_failed_flush_error)}},cN=e=>{let t=new Map;for(let n of e)YP(t,n);return[...t.entries()].map(([n,r])=>JP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},lN=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Ps(t.globalPmRoot),generated_at:S()}),dN=async(e,t)=>{let n=await Ps(t.globalPmRoot);await Xp(t.globalPmRoot);let r=await Ps(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:i,queue_drained:i,status:r,generated_at:S()}},mN=async(e,t)=>{let n=ZP(e.limit),r=await Z(t.queuePath),o=Yv(r),i=cN(o.entries),s=i.slice(0,n),a=await A(t.globalPmRoot),c=await aN(t.globalPmRoot,t.statePath,a.telemetry.retention_days),m=Object.entries(c).map(([u,p])=>{let f=Object.values(p.days);return{alias:u,canonical:p.canonical,count:f.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:f.map(_=>_.last_seen).sort().at(-1)}}).sort((u,p)=>p.count-u.count||u.alias.localeCompare(p.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:i.length>s.length,stats:s,alias_usage:m,zero_use_aliases:Hv.map(u=>u.alias).filter(u=>c[u]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:S()}},uN=async(e,t)=>Va(async()=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await $e(t.globalPmRoot,n,"telemetry:clear");let o=zt.join(t.globalPmRoot,jP),i=await G(o);return await GP.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await G(o),queue_exists_after:await G(t.queuePath),state_exists_after:await G(t.statePath),status:await Ps(t.globalPmRoot),generated_at:S()}},t.globalPmRoot),pN={status:lN,flush:dN,stats:mN,clear:uN};async function Jv(e,t){let n=XP(e.subcommand),r=ct(process.cwd());return pN[n](e,{globalPmRoot:r,queuePath:zt.join(r,zv),statePath:zt.join(r,Bv)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffa50b5b-d99f-5ab4-a70d-cbf12911a0f2")}catch{}})();var Xv=20;function fN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Xv;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Xv:t}function Xl(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let i=Yo(r.recorded_at,o.recorded_at);if(i!==0)return i;let s=r.run_id.localeCompare(o.run_id);return s!==0?s:r.kind.localeCompare(o.kind)}),n=fN();return t.length>n?t.slice(t.length-n):t}async function Ns(e){await se({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=Xl([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3570c976-1b25-501e-b51a-5ecfd1b70c15")}catch{}})();function Qv(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function Ql(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=Qv(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let i of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof i=="number"&&(!Array.isArray(o)||i>=o.length))return{found:!1,value:void 0};let s=Object.getOwnPropertyDescriptor(o,i);if(!s||!Object.hasOwn(s,"value"))return{found:!1,value:void 0};o=s.value}return{found:!0,value:o}}import{spawn as hw}from"node:child_process";import{cp as td,mkdir as Ms,mkdtemp as gw,open as nd,readdir as rd,rm as Jr,symlink as yw}from"node:fs/promises";import{tmpdir as vw}from"node:os";import V 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]="328c7577-364c-5869-aa92-199e56d2f6a7")}catch{}})();var Zv=100;function Zl(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function _N(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Zv?n:`${n.slice(0,Zv-3)}...`}function ew(e){return e.map((t,n)=>`${n+1}. ${_N(t)}`).join("; ")}function hN(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function gN(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function tw(e,t){let n=hN(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let i=[],s=[];for(let a=0;a<e.length;a+=1)gN(e[a],o)&&(s.push(e[a]),i.push(a+1));if(s.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${ew(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:s,selected_indexes:i,selected_count:s.length,skipped_count:e.length-s.length}}if(r==="only-index"){let o=Zl(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${ew(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="04ea3495-92b7-5518-b06c-a1668d368d66")}catch{}})();var Fs=20*1024*1024,yN=3e3,vN=1e4,wN=5e3,nw=120,bN=new Set(["locks","extensions","runtime"]),kN=new Set(["history","index","search","extensions","locks","runtime"]),SN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],EN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,AN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,TN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function id(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function CN(){return id("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",yN)}function IN(){return id("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",vN)}function RN(){return id("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",wN)}function ON(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function xN(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function sd(e){let t=0,n=0,r=0,o=0;for(let i of e){let s=i.execution_context;!s||s.is_pm_command!==!0||(t+=1,s.is_pm_tracker_read_command===!0&&(n+=1),s.mismatch_detected===!0&&(r+=1),s.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function PN(e){let t=e??"project";if(!at.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function Ds(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(cn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${cn.join(", ")}`,d.USAGE)}function NN(e){return dn(e??"source","--workspace-context")}function ww(e,t,n){return n?t:dn(e.workspace_context_mode,"linked test")??t}function bw(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ds(e.pm_context_mode)}function kw(e,t){return e==="auto"?t?"tracker":"schema":e}function LN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function $N(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function FN(e,t){let n={};if(!e)return n;for(let r of e){let o=Mr(r,t);if(o)for(let[i,s]of Object.entries(o))n[i]=s}return n}function MN(e,t){if(!e)return[];let n=[];for(let r of e){let o=Dr(r,t);o&&n.push(...o)}return[...new Set(n)]}function DN(e){let t=Us(e);return Cr(t).some(n=>rc(n)!==null)}function Sw(e){let t=Us(e);return Cr(t).some(n=>{let r=rc(n);if(!r)return!1;let o=__(r);return o?TN.has(o.subcommand):!1})}function Ls(e){if(e)return u_.has(e.subcommand)?qn(e.args,p_)?.subcommand:e.subcommand}function rw(e,t){if(e==="npx"||e==="bunx")return Pi(t)?.command;if(e==="pnpm")return Ls(qn(t,c_));if(e==="npm")return Ls(qn(t,l_));if(e==="yarn")return Ls(qn(t,d_));if(e==="bun")return Ls(qn(t,m_))}function $s(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function ed(e){return!e||!ic(e.command)&&!f_(e.command)?!1:xi(e.args)==="test-all"}var Ew=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),UN=new Set(["npx","bunx"]);function Aw(e){let t=e.split(" ").filter(s=>s.length>0),n=oc(t);if(n.length===0)return!1;let[r,...o]=n,i=Ew.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0?Aw(o.slice(s+1).join(" ")):!1}return ic(r)||sc(r)?xi(o)==="test-all":r==="node"&&o.length>0&&sc(o[0])?xi(o.slice(1))==="test-all":UN.has(r)?ed(Pi(o)):r==="pnpm"?ed(ac(o)):r==="npm"?ed(cc(o)):!1}function Tw(e){let t=Us(e);return Cr(t).some(n=>Aw(n))}function Cw(e){if(Tw(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function Us(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Iw(e){let t=e.split(" ").filter(s=>s.length>0),n=oc(t);if(n.length===0)return!1;let[r,...o]=n,i=Ew.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0&&Iw(o.slice(s+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?GN(o):jN(r,o)}function GN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function jN(e,t){return e==="npx"||e==="bunx"?$s(Pi(t)?.command):e==="pnpm"||e==="npm"?$s((e==="pnpm"?ac(t):cc(t))?.command)||$s(rw(e,t)):(e==="yarn"||e==="bun")&&$s(rw(e,t))}function qN(e){if(Tw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function KN(e){return e?e.map(zN):[]}function zN(e){let t=e.trim(),n=mg(t)?Zi(le(e,"--add"),"--add"):{command:t},r=he(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Cw(r),{command:r,path:he(n.path),scope:PN(n.scope),timeout_seconds:BN(he(n.timeout_seconds),he(n.timeout)),pm_context_mode:os(he(n.pm_context_mode),"--add"),workspace_context_mode:dn(he(n.workspace_context_mode),"--add"),env_set:Mr(he(n.env_set),"--add"),env_clear:Dr(he(n.env_clear),"--add"),shared_host_safe:rs(he(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:mn(he(n.assert_stdout_contains)),assert_stdout_regex:Hn(he(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:mn(he(n.assert_stderr_contains)),assert_stderr_regex:Hn(he(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:is(he(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:ss(he(n.assert_json_field_equals),"--add"),assert_json_field_gte:as(he(n.assert_json_field_gte),"--add"),note:he(n.note)}}function he(e){let t=e?.trim();return t&&t.length>0?t:void 0}function BN(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(pe(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function HN(e){return e?e.flatMap(t=>{let n=fg(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);Cw(o)}return n}):[]}function VN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=le(n,"--remove"),i=o.path!==void 0?"path":"command",s=o.path??o.command;if(!s?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:i,value:s.trim()}}return{kind:"either",value:n}}):[]}function WN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function YN(e){try{e.stdin?.end()}catch{}}function Rw(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=nw?t:`${t.slice(0,nw-3)}...`}function Ow(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function od(e){try{process.stderr.write(`${e}
30
- `)}catch{}}function JN(e,t){if(!Ow(t))return null;let n=Rw(e.command),r=Date.now();od(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let i=Date.now()-r;od(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},IN());return o.unref?.(),o}function XN(e,t,n,r){if(!Ow(r))return;let o=Rw(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";od(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${i}${u} command="${o}"`)}async function ow(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=hw("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function QN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function ZN(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await ow(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{ow(r)},CN()),t.forceKillTimer.unref?.()}}function eL(e){return new Promise(t=>{let n=!1,r=null,o=(i,s=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),s&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,s)=>{n||(r=setTimeout(()=>{o({code:i,signal:s},!0)},RN()),r.unref?.())}),e.on("close",(i,s)=>{o({code:i,signal:s})})})}function tL(e,t,n,r,o){return hw(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function iw(e){let t=await nd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Fs),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>Fs}}finally{await t.close()}}async function nL(e,t,n,r,o,i=process.cwd()){let s=Date.now(),a=await gw(V.join(vw(),"pm-linked-test-output-"));try{let c=V.join(a,"stdout.log"),m=V.join(a,"stderr.log"),[u,p]=await Promise.all([nd(c,"w"),nd(m,"w")]),f;try{f=tL(e,n,u.fd,p.fd,i)}catch(Y){throw await Promise.all([u.close(),p.close()]),Y}let _=eL(f),h;f.on("error",Y=>{h=Y.message}),await Promise.all([u.close(),p.close()]),YN(f);let y={heartbeat:JN(r,o),forceKillTimer:null,timedOutTimer:null},g=ZN(f,y),v=!1;y.timedOutTimer=setTimeout(()=>{v=!0,g()},t),y.timedOutTimer.unref?.();let{code:b,signal:k}=await _;QN(y);let[T,O]=await Promise.all([iw(c),iw(m)]),L=T.truncated||O.truncated,$=L?`
31
- [pm linked-test output truncated at ${Fs} bytes per stream; the child process continued to completion]
32
- `:"",K={stdout:`${T.text}${$}`,stderr:O.text,exitCode:b,signal:k,timedOut:v,maxBufferExceeded:!1,outputTruncated:L,spawnError:h};return XN(r,K,s,o),K}finally{await Jr(a,{recursive:!0,force:!0})}}function rL(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Fs} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function oL(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
33
- `);return SN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>EN.test(n)&&AN.test(n))}function iL(e){return oL(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function sL(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Gs(e){let t=sL();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function sw(e,t){for(let[n,r]of Object.entries(t.env_set))ln.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)ln.has(n.toUpperCase())||delete e[n]}function aL(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function cL(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function lL(e,t,n){return{env_set:FN(e,"--env-set"),env_clear:MN(t,"--env-clear"),shared_host_safe:n===!0}}async function er(e,t,n=!1,r=Ms){if(await G(e))try{await ir("seed_linked_test",async()=>{if(await r(V.dirname(t),{recursive:!0}),n){await td(e,t,{recursive:!0,force:!0});return}await td(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&Ct(o))return;throw o}}async function aw(e,t,n){await er(ue(n.projectPmRoot),ue(e)),await er(V.join(n.projectPmRoot,"extensions"),V.join(e,"extensions"),!0),await er(ue(n.globalPmRoot),ue(t)),await er(V.join(n.globalPmRoot,"extensions"),V.join(t,"extensions"),!0)}async function cw(e,t){if(!await G(e))return;let n=await rd(e,{withFileTypes:!0});for(let r of n){if(bN.has(r.name))continue;let o=V.join(e,r.name),i=V.join(t,r.name);if(r.isDirectory()){await er(o,i,!0);continue}r.isFile()&&await er(o,i)}}async function lw(e,t){let n=await Z(ue(e));if(n===null||await G(ja(e)))return;let r=await A(t);await Jr(ja(t),{force:!0}),await Jr(ue(t),{force:!0}),await nt({pmRoot:t,filePath:ue(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Zn(e){if(!await G(e))return 0;let t=0,n=await rd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||kN.has(r.name))continue;let o=V.join(e,r.name),i;try{i=await rd(o,{withFileTypes:!0})}catch{continue}for(let s of i)s.isFile()&&Hd.some(a=>s.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function dL(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function mL(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function uL(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?dt(e,t):Object.is(e,t)}function pL(e,t,n){let r=[];r.push(...dw("stdout",t,e.assert_stdout_contains)),r.push(...mw("stdout",t,e.assert_stdout_regex)),r.push(...dw("stderr",n,e.assert_stderr_contains)),r.push(...mw("stderr",n,e.assert_stderr_regex)),r.push(...fL(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(o)){let u=Ql(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=mL(m);uL(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,m]of Object.entries(i)){let u=Ql(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<m&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${m}, actual ${u.value})`)}return r}function dw(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function mw(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(i){r.push(`${e} regex assertion is invalid: /${o}/ (${i instanceof Error?i.message:String(i)})`)}return r}function fL(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var _L=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],hL=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function gL(e,t){let n=`${e}
34
- ${t}`;for(let r of _L)if(r.regex.test(n))return{code:r.code};return null}function yL(e,t){let n=`${e}
35
- ${t}`;return hL.some(r=>r.test(n))}function uw(e){let t=Us(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Cr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&Iw(n))}function vL(e){return{root:e,schemaProjectPmPath:V.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:V.join(e,"schema","global"),trackerProjectPmPath:V.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:V.join(e,"tracker","global"),workspaceSnapshotRoot:V.join(e,"workspace","project"),workspaceIsolatedRoot:V.join(e,"workspace","isolated")}}function wL(e,t,n){return e.some(r=>ww(r,t,n)==="snapshot")}async function bL(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await Ms(V.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await td(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let i=V.relative(t,o);return i?!i.split(V.sep).some(s=>n.has(s)):!0}});let r=V.join(t,"node_modules");await G(r)&&await yw(r,V.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function kL(e,t){let n=V.join(e,".agents"),r=V.join(n,"pm");await Ms(n,{recursive:!0}),await Jr(r,{recursive:!0,force:!0}),await yw(t,r,process.platform==="win32"?"junction":"dir")}async function SL(e,t=Nr,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function EL(e,t,n){t&&(await aw(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await aw(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await cw(t.projectPmRoot,e.trackerProjectPmPath),await cw(t.globalPmRoot,e.trackerGlobalPmPath),await lw(t.projectPmRoot,e.trackerProjectPmPath),await lw(t.globalPmRoot,e.trackerGlobalPmPath)))}function AL(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&Sw(o),s=n?.autoPmContext===!0&&i?"auto":bw(r,t,n?.overrideLinkedPmContext===!0);return kw(s,i)==="tracker"})}async function TL(e,t){return{sourceProjectItemCount:t?await Zn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Zn(t.globalPmRoot):0,schemaProjectItemCount:await Zn(e.schemaProjectPmPath),schemaGlobalItemCount:await Zn(e.schemaGlobalPmPath),trackerProjectItemCount:await Zn(e.trackerProjectPmPath),trackerGlobalItemCount:await Zn(e.trackerGlobalPmPath)}}function CL(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,s=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":s;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:s,source_workspace_root:a,trust:e.trust}}async function IL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ds(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?DN(n):!1,o=r&&n?Sw(n):!1,i=e.options?.autoPmContext===!0&&o,s=i?"auto":bw(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=kw(s,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await kL(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await lc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await lc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:CL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:s,effectivePmContextMode:a,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function pw(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Xr(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function RL(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function OL(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return RL(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function xL(e){if(!e.linkedTest.command)return pw(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=qN(e.linkedTest.command);return t?pw(e.linkedTest,e.executionContext,t):null}function PL(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Xr(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Xr(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function NL(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=$N({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Xr(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function LL(e){let t=xL(e);if(t)return t;let n=OL(e);if(n)return n;let r=PL(e);if(r)return r;let o=NL(e);return o||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!LN(e.linkedTest)?Xr(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function $L(e){let t=cL(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return sw(n,e.runtimeDirectives),sw(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&aL(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Er]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Er]="read_only"),n}function FL(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function fw(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function ML(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:dL(e.execution),failure_category:iL(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:rL(e.execution,e.timeoutMs)}}function DL(e){if(e.options?.failOnEmptyTestRun===!0||uw(e.linkedTest.command??"")){let n=gL(e.execution.stdout,e.execution.stderr);if(n)return fw({...e,emptyRunSignal:n});if(uw(e.linkedTest.command??"")&&!yL(e.execution.stdout,e.execution.stderr))return fw({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=pL(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Xr(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):FL(e.linkedTest,e.executionContext,e.execution)}async function UL(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await nL(t,n,$L(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?DL({...e,execution:r}):ML({...e,execution:r,timeoutMs:n})}async function ad(e,t,n){let r=[],o=await gw(V.join(vw(),"pm-linked-test-")),i=vL(o),s=Ds(n?.pmContext),a=NN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=lL(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=g_(),f=AL(e,s,n),_=wL(e,a,n?.overrideLinkedWorkspaceContext===!0),h=await h_(p);try{await SL(i,Nr,f),await Ms(i.workspaceIsolatedRoot,{recursive:!0}),await EL(i,u,f),_&&await bL(i,p);let y=await TL(i,u);for(let g=0;g<e.length;g+=1){let v=e[g],b=ww(v,a,n?.overrideLinkedWorkspaceContext===!0),k=await IL({linkedTest:v,layout:i,counts:y,sourceRoots:u,runLevelPmContextMode:s,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:b,currentSourceRef:h,sourceWorkspaceRoot:p}),T=LL({linkedTest:v,executionContext:k.executionContext,runLevelPmContextMode:s,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await UL({linkedTest:v,index:g,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Jr(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function GL(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await q(n,t,r.id_prefix,r.item_format,o);if(!i)throw new l(`Item ${t} not found`,d.NOT_FOUND);let s=await ie(i,{schema:r.schema});return{itemId:i.id,tests:s.document.metadata.tests??[],testRuns:s.document.metadata.test_runs??[],changed:!1,removed:0}}function jL(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function qL(e,t){let n=[...e];for(let r of t)n.some(o=>jL(o,r))||n.push(r);return n}function KL(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,s)=>r.has(s+1)?!1:!t.some(a=>a.kind==="command"?i.command===a.value:a.kind==="path"?i.path===a.value:i.command===a.value||i.path===a.value));return{tests:o,removed:e.length-o.length}}function zL(e,t,n,r){return KL(qL(e,t),n,r)}function BL(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function HL(e){if(BL(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function VL(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:s,removes:a,removeIndexes:c}=e;if(s.length===0&&a.length===0&&c.length===0)return GL({id:t,pmRoot:r,settings:o,typeToFolder:i});let m=0,u=await se({pmRoot:r,settings:o,id:t,op:s.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=zL(f,s,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:dt(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function WL(e,t){HL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Zl(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?tw(t,n):void 0,o=e.timeout===void 0?void 0:pe(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:Ds(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function YL(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await ad(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:ct(process.cwd())}})}function JL(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=sd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function XL(e){let t=xN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=S(),i=Yr(e.options.measure,o);return{run_id:ON("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:i.length>0?i:void 0,executions:e.runResults.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}}async function QL(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:s,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!i)return;let m=XL({options:t,runStartedAt:i,runResults:s,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:m,receipt:{recorded:!1,reason:"tracking_disabled",run_id:m.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Ns({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),{entry:m,receipt:{recorded:!0,reason:"recorded",run_id:m.run_id}}}catch(u){return c.push(`test_result_tracking_failed:${o}:${u instanceof Error?u.message:String(u)}`),{entry:m,receipt:{recorded:!1,reason:"write_failed",run_id:m.run_id}}}}function _w(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),s=e.metricBelow.slice(o+1).trim(),a=Number(s);if(o<=0||i.length===0||s.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=Fv(t,i,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Mv(t,e.metricDiff)}}async function ZL(e,t,n){if(e.acknowledgeLinkedTests===!0)return y_(t,n,S())}function e$(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:s,recording:a,measurementProjection:c}=e;return{ok:n.every(m=>m.status!=="failed")&&i!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:r,selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:s.length>0?s:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function js(e,t,n){let r=Lt(),o=E(process.cwd(),n.path);await I(o);let i=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Yr(t.measure,"validation"),_w(t,[],void 0);let s=x(i,R()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...KN(a),...HN(c)],p=await Kn(u,C(t.author,i.author_default),S())??[],f=VN(m),_=WN(t.removeIndex),h=await VL({id:e,options:t,pmRoot:o,settings:i,typeToFolder:s.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=WL(t,h.tests),g=await ZL(t,o,h.tests),v=t.run===!0?S():void 0,b=await YL({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests}),k=Gs(b),T=t.run===!0&&t.failOnSkipped===!0&&b.some(Y=>Y.status==="skipped"),O=JL(t,y.runSelection,b);g&&O.push(`linked_test_trust_acknowledged:${g.acknowledged}`);let L=await QL({options:t,pmRoot:o,settings:i,itemId:h.itemId,runStartedAt:v,runResults:b,failOnSkippedTriggered:T,warnings:O}),$=L?.receipt.recorded?Xl([...h.testRuns,L.entry]):h.testRuns,K=_w(t,$,L?.entry);return e$({item:h,runResults:b,failureCategories:k,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:O,recording:L,measurementProjection: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]="e3e3a1d4-4552-5f3c-9b02-c33ae72ea32b")}catch{}})();var t$=(e,t)=>{if(e===void 0)return;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},n$=e=>{if(e===void 0)return;let t=pe(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},xw=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},r$=e=>e instanceof Error?e.message:String(e),o$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},i$=e=>e.trim().replaceAll(/\s+/g," "),s$=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),a$=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),c$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},l$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},qs=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Pw=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),d$=e=>typeof e=="number"?e:void 0,m$=e=>{let t={assert_stdout_contains:qs(e.assert_stdout_contains),assert_stdout_regex:qs(e.assert_stdout_regex),assert_stderr_contains:qs(e.assert_stderr_contains),assert_stderr_regex:qs(e.assert_stderr_regex),assert_stdout_min_lines:d$(e.assert_stdout_min_lines),assert_json_field_equals:Pw(e.assert_json_field_equals),assert_json_field_gte:Pw(e.assert_json_field_gte)};return JSON.stringify(t)},u$=e=>{let t=cd(e.command);return t!==void 0?`command:${e.scope}:${i$(t)}`:`path:${e.scope}:${cd(e.path)??""}`},Nw=e=>{let t=s$(e.env_set),n=a$(e.env_clear),r=c$(e.pm_context_mode),o=l$(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",s=m$(e);return`${u$(e)}:${t}:${n}:${r}:${o}:${i}:${s}`},p$=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,f$=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},_$=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Ks=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
36
- `)}catch{}},h$=async(e,t,n)=>{let r=[],o=0;for(let i of e){let s=await js(i.id,{run:!1},{...t,path:n});o+=s.tests.length,r.push({item:i,tests:s.tests})}return{itemTests:r,linkedTests:o}},g$=async e=>{let t=F(e.settings.schema),n=x(e.settings,R()),r=t$(e.options.status,t),o=xw(e.options.limit,"--limit"),i=xw(e.options.offset,"--offset")??0,a=(await fe(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},y$=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Nw(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,p$(t.get(o),r.timeout_seconds))}return t},v$=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Nw(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await ad(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],i=0,s=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[i];return i+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=f$(s),c=Gs(s),m=await k$(e,a,s,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:s,failure_categories:c}}},w$=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),b$=e=>e?!0:void 0,k$=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=w$(t,r.options);await Ns({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:S(),recorded_at:S(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:b$(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${r$(o)}`]}return[]},S$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},cd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},E$=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:ct(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:y$(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:o$(),trackingAttempt:S$(),trackingResumedFrom:cd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),A$=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Gs([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},T$=async(e,t,n)=>{for(let[r,o]of e.entries()){Ks(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let i=await v$(o,t);_$(n.failureCategories,i.failureCategories),n.passed+=i.passed,n.failed+=i.failed,n.skipped+=i.skipped,n.trackingWarnings.push(...i.trackingWarnings),n.results.push(i.result),Ks(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${i.failed===0?"passed":"failed"} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`)}},C$=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=sd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},I$=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),R$=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),O$=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await g$({pmRoot:n,settings:r,options:e}),i=n$(e.timeout),s=S(),a=await h$(o.filteredItems,t,n);return Ks(e,R$({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:s}},x$=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},Lw=async(e,t)=>{let n=await O$(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=A$(e,n.linkedTests,n.filteredItems),i=E$({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await T$(n.itemTests,i,r),C$(e,r);let s=x$({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Ks(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),I$({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="419a061f-e181-5b18-9e3a-d22cc5aff416")}catch{}})();function $w(e,t,n){let r;if(typeof e.lines=="string")r=Ci(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=Ci(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6f4c40f-50cf-568f-8a45-860ac4be3c97")}catch{}})();function Pe(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b86373f-26a3-5893-95dc-e794fcc1afa1")}catch{}})();function P$(e){let t=w(e.args,"subcommand")??Pe(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ge(n)}}function N$(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=wn({list:()=>wf(t.global),show:()=>bf(r,t.global),"show-status":()=>kf(r,t.global),"list-fields":()=>Af(t.global),"show-field":()=>Tf(r,t.global),"remove-type":()=>hf(r,{author:o,force:i},t.global),"remove-field":()=>Ef(r,{author:o,force:i},t.global),"remove-status":()=>vf(r,{author:o,force:i},t.global),"apply-preset":()=>Cf(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function L$(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Sf(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:s===void 0?void 0:ge(s),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:ge(a),author:r,force:o},t.global)}function $$(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.role??t.options.role;return yf(n,{role:s===void 0?void 0:ge(s),alias:i,description:w(t.args,"description")??w(t.options,"description"),order:Fe(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function F$(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return _f(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:i,author:r,force:o},t.global)}function M$(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,s=w(t.args,"to")??Pe(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:s}:n==="rename-field"?{kind:"rename-field",from:r??"",to:s,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:s};return pf(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function Fw(e){let t=P$(e);Np(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Tn.find(o=>o===t.subcommand);if(n)return uf(n,t.name,{definition:e.args.definition??e.options.definition,policy:w(e.args,"policy")??w(e.options,"policy"),message:w(e.args,"message")??w(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=N$(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return M$(t);if(t.subcommand==="add-field")return L$(t);if(t.subcommand==="add-status")return $$(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?If({minCount:Fe(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):F$(t);throw Te({command_path:"schema",token:t.subcommand,allowed:ff,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d5136ee1-7446-5fbf-b782-bc58b5323c64")}catch{}})();function zs(e){return w(e.args,"target")??w(e.options,"target")}function we(e,t=e.options){return e.id??Pe(t,"id")}async function D$(e){let t=Rn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Ac(await ht(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function U$(e){let t=Pe(e.args,"query"),n=Rn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Ac(await Or(t,n,e.global),n)}async function G$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await jt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function j$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Se(await Kc(we(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function q$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await ot(we(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function K$(e){let t=qi(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),yh(we(e),t,e.global)}function Mw(e,t){return Bf($w(e.options,t,Fe),e.global)}function z$(e){let t=ge(e.options.lookupPath);if(t&&t.length>0)return Mw(e,t);let n=we(e);return e.options.discover===!0?nc(n,Si(e.options),e.global):zf(n,Ar(e.options),e.global)}function B$(e){return Jv({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:$f(e.args,e.options)},e.global)}function H$(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Tr(e.global,t)}function V$(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Gh(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function W$(e){let t=e.options;return I_(C_(t),e.global)}function Y$(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function J$(e){let t=w(e.args,"subcommand")??Pe(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=_e(e.args,e.options),i=await yy({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:X$(e),reorderTo:Y$(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&Pf(e.args)&&(i.mutation_receipt=Ss(i,void 0)),t==="show"?i:Se(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function X$(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function Q$(e){let t=w(e.args,"subcommand")??Pe(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),i=wn({list:()=>Ny(),show:()=>Ly(r),lint:()=>$y(r),apply:()=>Fy(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!i)throw Te({command_path:"profile",token:t,allowed:Py,exit_code:64});return i()}async function Z$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await Zh(we(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function eF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options);return Se(await Sy(Ai(n),e.global),{changedFields:t})}async function tF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Se(await lg(Ei(o),e.global),{changedFields:t})}async function nF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=w(r,"target")??Pe(e.args,"target");return Se(await sn(we(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function rF(e){let t={...e.args,...e.options};return Hf(Pe(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Uf(t),e.global)}function oF(e){return jf(E(process.cwd(),e.global.path),{...e.args,...e.options})}var Dw={init:e=>Nr(w(e.args,"prefix"),e.global,e.options),context:e=>uc(Rn("context",e.options),e.global),next:e=>Rr(Rn("next",e.options),e.global),eval:hv,events:gv,merge:yv,workspace:vv,meet:Rs,event:Rs,remind:Rs,list:D$,get:e=>{let t=we(e);return fc(t,e.global,Rn("get",e.options,[t]))},search:U$,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ge(e.options.status);return tc(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:w(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Fe(e.options.limit,"limit")})},create:G$,copy:j$,focus:e=>nl(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:q$,"item-reopen":iy,restore:nF,claim:ny,release:oy,"start-task":e=>_n(e,"start_task"),"pause-task":e=>_n(e,"pause_task"),"close-task":e=>_n(e,"close_task"),close:ry,comments:K$,notes:e=>Ey(we(e),qi(e.options),e.global),learnings:e=>Qh(we(e),qi(e.options),e.global),files:z$,docs:e=>Kf(we(e),Ar(e.options),e.global),test:e=>js(we(e),e.options,e.global),"test-all":e=>Lw(e.options,e.global),telemetry:B$,validate:e=>Ni(e.options,e.global,{runUpdate:(t,n,r)=>ot(t,n,r)}),health:H$,assurance:e=>v_(e.args,e.options,e.global),contracts:e=>yc(e.options,e.global),config:V$,activity:W$,aggregate:e=>pc(e.options,e.global),extension:e=>Un(zs(e),e.options,e.global),package:e=>Un(zs(e),e.options,e.global),install:e=>Un(zs(e),{...e.options,install:!0},e.global),upgrade:e=>b_(zs(e),e.options,e.global),delete:e=>tl(we(e),e.options,e.global),deps:e=>qf(we(e),e.options,e.global),graph:rF,"files-discover":e=>nc(we(e),e.options,e.global),"files-lookup":e=>Mw(e,ge(e.options.paths)),history:e=>R_(we(e),e.options,e.global),"history-redact":e=>Xh(we(e),e.options,e.global),"history-repair":Hh,"history-compact":Vh,"history-attest":e=>k_(e.options,e.global),"history-author-acknowledge":oF,plan:J$,schema:Fw,profile:Q$,stats:e=>Vl(e.global,wv(e.options)),append:Z$,"update-many":eF,"close-many":tF,gc:e=>w_(e.global,e.options)};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8137f8b-745a-5ef5-9e7e-14b7d032c1ea")}catch{}})();var iF=new Map;function ld(){iF.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c84b11c-502f-5c33-a757-5757402357b4")}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]="b841f903-6276-5067-842f-6a6bff114cec")}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]="4277a72c-f012-55d2-9e18-c9a836d829d6")}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]="aba4af26-98d3-53aa-8b23-1be7c90a38d1")}catch{}})();function Uw(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5b106ed0-ef19-58a4-a7d0-bd0988482f58")}catch{}})();var jw=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:rp().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],Gw=new Map;for(let e of jw){Gw.set(e.id,e);for(let t of e.aliases)Gw.set(t,e)}function dd(){return jw.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a7cf539-2663-5265-90e8-c2aa9926a62a")}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]="be171aef-09e7-5f87-9605-1d47ca665440")}catch{}})();var a5=[...no],c5=[...ro],md=new Set(Jt.filter(e=>e.hidden).map(e=>e.alias)),qw=np("full").filter(e=>!e.includes(" ")&&!md.has(e)),sF=N(fo),aF=N(_o),cF=N(ko),lF=N(Co),Kw=ur("restore",Rt("restore")),zw=ur("history-attest",Rt("history-attest")),dF=N(Io),mF=N(Hm),uF=N(Vm),pF=N(To),fF=N(Po),_F=N(Ro),hF=N(Oo),gF=N(bo),ud=[...new Set(ke.map(e=>e.canonical_argv[0]))],Bw=[...new Set(ke.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],l5=new Set(uo.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),Hw=ke.filter(e=>e.canonical_argv[0]==="history"),yF=Hw.map(e=>e.canonical_argv[1]).join(" ");var vF=Hw.map(e=>({...e,flags:N(Rt(e.alias))})),wF=N(ho),bF=N(go,!1),kF=N(xo),SF=N(dr),EF=N(mr),AF=N(Fo),TF=N(Lo),CF=N(Eo),IF=N($o),RF=N(No),OF=N(Mo),xF=N(So),PF=N(Ao),NF=N(vo),LF=N(Do),$F=N(yo),pd=`${Tn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var FF=N(Uo),MF=`${FF} bash zsh fish`,fd=Hs(dd()),Bs="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",_d=`${Bs} upgrade`,DF=N(wo),UF=N(cr),GF=N(lr);var jF=N(Rt("close")),qF=N(Rt("close-task")),KF=N(Rt("release")),zF=N(Rt("claim"));var Vw=po.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),hd=[...Wo].join("|"),gd=[...Wo].map(e=>`${e}=*`).join("|"),yd=[...Vw.split(" ").filter(e=>!Wo.has(e)),"-h","-V"].join("|");function Hs(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2dba61cf-0757-5b46-b86c-e5b7a1c733ae")}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]="1cf1ab58-6aaf-5d9b-9681-0a070119c791")}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]="818bb54f-06ad-587f-86d6-4eaee9e4966c")}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]="c1fb3981-3bae-5f63-861a-ee689a9ffd36")}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]="2c2a4576-a5d8-57c1-84e8-ca8b9019c84e")}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]="e7f8a7ea-3ec2-521b-ad52-45b655208f06")}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]="196dc906-149b-5280-b054-81d1e178100f")}catch{}})();var Zw=Symbol("pm.active-extension-host-context");function Ge(e){return{fullChangedFields:!0,options:e}}var U=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[Zw]=!0,n}run(t,n={}){return eb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return mh(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Ja(await this.list(Ya(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...Ge(Ut(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:Ut(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ge(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ge(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ge(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ge(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ge(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ge(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ge(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ge(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Ge(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ge(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ge(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ge(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function ZF(e={},t={}){return new U(t).context(e)}function eM(e={},t={}){return new U(t).list(e)}function tM(e={},t={}){return new U(t).listAllComplete(e)}function nM(e,t={},n={}){return new U(n).search(e,t)}function rM(e,t={},n={}){return new U(n).get(e,t)}function oM(e={},t={}){return new U(t).next(e)}function iM(e={},t={}){return new U(t).aggregate(e)}function sM(e,t={},n={}){return new U(n).comments(e,t)}function aM(e,t={},n={}){return new U(n).notes(e,t)}function cM(e,t={},n={}){return new U(n).learnings(e,t)}function lM(e,t={},n={}){return new U(n).files(e,t)}function dM(e,t={},n={}){return new U(n).filesDiscover(e,t)}function mM(e,t={},n={}){return new U(n).docs(e,t)}function uM(e,t={},n={}){return new U(n).deps(e,t)}function pM(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function fM(e,t,n={},r={}){return new U(r).append(e,t,n)}function _M(e={},t={}){return new U(t).create(e)}function hM(e,t={},n={}){return new U(n).update(e,t)}function gM(e,t,n={},r={}){return new U(r).reopen(e,t,n)}function yM(e,t,n={},r={}){return new U(r).close(e,t,n)}function vM(e,t={},n={}){return new U(n).claim(e,t)}function wM(e={},t={}){return new U(t).claimNext(e)}function bM(e,t={},n={}){return new U(n).release(e,t)}function kM(e,t={},n={}){return new U(n).copy(e,t)}function SM(e,t={},n={}){return new U(n).delete(e,t)}function EM(e,t,n={},r={}){return new U(r).restore(e,t,n)}function AM(e,t={},n={}){return new U(n).focus(e,t)}var Xw=Lu(),TM=new QF;function Vs(){Sa(Wd()),Ea(Yd()),Aa(Jd()),Ta(Xd()),Ca(Qd()),Ia(Zd()),Ra(em())}async function CM(e,t,n,r){return $u(()=>t===void 0?Xw.read(()=>Qw(e,n,r)):Xw.write(()=>RM(t,()=>Qw(e,n,r))))}async function Qw(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Vs(),wc({pmRoot:r},()=>n(null));if(!await G(ue(r)))return Vs(),n(null);let o=null,i;try{let s=await A(r),a=await sr({pmRoot:r,settings:s,cwd:t,noExtensions:!1}),c=await ar({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},Sa(c.hooks),Ea(c.commands),Aa(c.parsers),Ta(c.preflight),Ca(c.services),Ia(c.renderers),Ra(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(s){Vs(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",s)}try{return await wc({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Vs(),i&&await fa(i.loadResult,i.activationResult).catch(()=>{})}}async function IM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let i=Gn(e),a=o.registrations.commands.find(m=>Gn(m.action)===i)?.command??o.commands.handlers.find(m=>Gn(m.command)===i)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await Vo({command:Za(a),args:ge(n.args??t.args),options:ec(t,n),global:r,pm_root:o.pmRoot,sdk:sh(o.pmRoot,U.forActiveExtensionHost({pmRoot:o.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function RM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function OM(e){let t=Pe(e,"action"),n=Gn(t),r=wn(ph,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...ua(e.options)}),o==="package"&&(i.options={...ua(i.options),vocabulary:"package"}),{action:o,args:i}}async function eb(e){let t=OM(e),n=Xa(t.args),r=Mf(t.action),o=w(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[Ec]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(i,n.path));try{return t.action==="history-attest"?await vd(t.action,t.args,n,null):e[Zw]===!0||TM.getStore()===!0?await vd(t.action,t.args,n,null):await CM(n,o,i,s=>vd(t.action,t.args,n,s))}finally{r&&ld()}}async function vd(e,t,n,r){let o=Qa(t,e);Na(e,o),Gu(e,o);let i={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},s=wn(Dw,e),a=s?await s(i):await IM(e,t,o,n,r);if(e==="history-attest")return a;{o.resolvedOutputFormat="json";let c=zu(e,o,a);return await oh(E(process.cwd(),n.path),c),c}}var xM={closeManyOptionsFromFlat:Ei,extensionOptionsFromArgs:ec,globalOptions:Xa,mutationListOptions:Df,normalizeActionName:Gn,normalizeCommandPath:Za,normalizeMcpUpdateOptions:Gf,normalizeMcpOptionsArrays:Ff,optionsWithAuthor:Qa,readRequiredString:Pe,readScalarString:Nf,readScalarStringAllowBlank:Lf,readStringArray:ge,updateManyOptionsFromFlat:Ai,withAddNoteOption:Ar,withFilesDiscoveryOptions:Si,withMutationCompaction:_e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=xM);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3eaa41f7-77a1-5838-8a2f-2ab6a49c21ef")}catch{}})();export{On as AGENT_PROVENANCE_DIMENSIONS,up as BASELINE_ITEM_FORMAT_VERSION,ek as BUILTIN_AGENT_PROVENANCE_ADAPTERS,pr as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,no as BUILTIN_ITEM_TYPE_VALUES,oo as CONFIDENCE_TEXT_VALUES,pp as CURRENT_ITEM_FORMAT_VERSION,Vt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,kn as ISSUE_SEVERITY_VALUES,Nd as ITEM_TYPE_VALUES,bc as PM_CLI_EXPECTED_ERROR_NAME,Gb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Db as PM_READ_OUTPUT_DIMENSIONS,Ub as PM_READ_OUTPUT_OPTION_FLAGS,xa as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,bn as RISK_VALUES,fk as SEMANTIC_ATTRIBUTION_LIMITS,ro as STATUS_VALUES,Zb as agentSessionEnvironment,iM as aggregate,Bl as analyzeAgentProvenanceDescriptorCoverage,Yb as analyzeSdkCliParameterCompleteness,fM as append,qb as applyReadOutputDimensions,Hb as applyReadOutputSessionReferences,Vb as attachReadOutputSessionReceipt,Jb as boundAgentEpisodeIdentity,et as canonicalDocument,vM as claim,wM as claimNext,hp as classifyItemFormatVersion,yM as close,sM as comments,ZF as context,kM as copy,_M as create,ih as createPmCliExpectedError,Mb as decodeReadOutputContinuationCursor,SM as deleteItem,uM as deps,ak as detectAgentIdentity,dk as detectHarnessIdentity,ck as diagnoseAgentIdentity,mM as docs,fp as effectiveItemFormatVersion,Uw as emptyImportedDocument,Fb as encodeReadOutputContinuationCursor,uP as evaluateSemanticAttributionCoverage,uk as explainSourceTraceability,lM as files,dM as filesDiscover,AM as focus,rM as get,pM as graph,pP as groupHistoryByEpisode,ey as isAlreadyClaimedError,Gi as isPmCliExpectedError,Kb as isReadOutputBudgetExceeded,cM as learnings,eM as list,nk as listAgentProvenanceAdapters,tM as listAllComplete,oM as next,ok as normalizeAgentProvenanceAdapterValue,_p as normalizeItemFormatVersion,qe as normalizeItemId,ee as normalizeStatusInput,aM as notes,S as nowIso,Bb as parseReadOutputSession,Ci as parseSourceLineRange,ei as readAuthorEnvironment,Wb as readOutputSessionRemainingTokens,dc as recordClaimSemanticAttribution,$i as recordFocusSemanticAttribution,mc as recordReleaseSemanticAttribution,rk as registerAgentProvenanceAdapters,tk as registerHarnessSignalDescriptors,bM as release,gM as reopen,Xb as resolveAgentSessionContextFromSignals,mk as resolveAuthorIdentity,Rv as resolveHistoryEpisodeGroupIdentity,jb as resolveReadOutputDimensions,zb as resolveReadOutputEncoding,Pa as resolveReadOutputSurface,pk as resolveSemanticLineageIds,EM as restore,eb as runAction,Qb as runWithAgentSessionContext,ik as runWithHarnessDetectionSignals,sk as runWithWorkspaceHarnessSignalDescriptors,nM as search,_k as semanticAttributionAffinity,Be as serializeItemDocument,mP as summarizeAgentModelProvenance,Hl as summarizeAgentProvenance,hM as update,Na as validateReadOutputOptions,lk as writeAuthorEnvironment};
19
+ `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.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]="86c929a6-644f-5b8e-a12b-04a73b4f4b60")}catch{}})();var pT=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function rg(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 Gc(e,t){return jc(e,t,{operation:"close"})}function jc(e,t,n){let r=rg(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 qc(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"),s=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),s&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let m=new Set(i),u=o.filter(p=>!m.has(p));u.length>0?e.dependencies=u:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,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:a,warnings:[]}:{changedFields:a,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]="49e375b7-49a8-5b6f-89c8-be70d334b78f")}catch{}})();var fT=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function _T(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 og(e){let t=[];for(let n of fT){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function ig(e,t,n={}){let r=og(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(a=>`--${a.key.replaceAll("_","-")}`),s=["--pm-path",t,"update",e.id,...r.flatMap((a,c)=>[i[c],o[a.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:Zt(s),suggested_retry_args:s}}async function hT(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 gT(e){return typeof e!="string"||e.trim().length===0}async function yT(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,R()),s=new Map,a=async m=>{if(s.has(m))return s.get(m)??null;let u=await q(e,m,t.id_prefix,t.item_format,i.type_to_folder);if(!u)return s.set(m,null),null;let{document:p}=await se(u,{schema:t.schema});return s.set(m,p.metadata),p.metadata},c=await a(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 hT(a,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 vT(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 wT(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=tf(e),i=t.trim().toLowerCase(),s=n.blocked_statuses;return e.filter(a=>s.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(i)).filter(({blockerIds:a})=>a.every(c=>{if(c===i)return!0;let m=r.get(c);return m!==void 0&&re(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function bT(e,t,n,r,o,i){let s=wT(n,r,i),a=[];for(let c of s)try{let m=await ae({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=i.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function kT(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 s=o.trim();s.length!==0&&(e[i]=s,n.push(i))}return n}function ST(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)gT(e[o])&&(e[o]=i,n.push(o));return n}function ET(e,t,n,r){let o=[];if(t!=="off"){let i=og(e);if(i.length>0){let s=i.map(a=>a.label);if(t==="strict"){let a=i.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${s.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,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}:${s.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 AT(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function TT(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function CT(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:ig(e,t.pmRoot,t.options)});let n=kT(e,t.options),r=ST(e,t.duplicateOf),o=ET(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 s=["status","closed_at",...i?["completed_at"]:[],...AT(e,t.closeReason),...n];if(Zp(e)&&(e.plan_mode="completed",s.push("plan_mode")),t.duplicateOf!==void 0){s.push("duplicate_of");for(let c of r)s.includes(c)||s.push(c)}s.push(...TT(e));let a=qc(e,t.lifecyclePolicy);return s.push(...a.changedFields),o.push(...a.warnings),{changedFields:s,...o.length>0?{warnings:o}:{}}}async function sg(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),s=F(i.schema),a=C(n.author,i.author_default),c=x(i,R()).type_to_folder,m=await q(o,e,i.id_prefix,i.item_format,c);if(!m)throw await _t(o,e,i.id_prefix,c);let u=await yT(o,i,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??i.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Gc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=_T(n.validateClose)??i.governance.close_validation_default,h=await fe(o,i.item_format,c,void 0,i.schema),y=vT(h,m.id,s),g=S(),v=n.completedAt===void 0?g:ie(n.completedAt,new Date(g),"completed-at"),b=await ae({pmRoot:o,settings:i,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(T){return CT(T.metadata,{pmRoot:o,statusRegistry:s,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:v,lifecyclePolicy:p})}}),k=_==="warn"?ig(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...k?{recovery:k}:{},warnings:[...b.warnings,...await bT(o,i,h,m.id,a,s)]}}function vt(e,t,n,r){return sg(e,t,n,r)}import IT from"fast-json-patch";import Kc 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]="85aa928d-92b8-5f67-8482-0fe5715fef45")}catch{}})();async function ag(e,t,n){let r=await Vp(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:cg(n),recovered:!0}}function RT(e,t){return zp(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function cg(e){let t=Wa(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:tt(nt(t))}async function OT(e,t,n,r){let o=await tn(e,t,n,r),i=o.located?await Up({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function xT(e,t){let n=hr(e),r=hr(t),o=IT.compare(n,r),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function PT(e){let t=await l_({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>ag(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function NT(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:cg(t),originalRaw:null}}function LT(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 $T(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await te(e.existingItemPath,e.resolvedOriginalRaw),await Kc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await te(e.existingItemPath,e.resolvedOriginalRaw);return}await Kc.rm(e.restoredItemPath,{force:!0})}async function FT(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 sn(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let i=await A(o),s=x(i,R()),a=await OT(o,e,i,s.type_to_folder),c=a.id,{raw:m,entries:u}=await wp(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=RT(t,u),f=Bp(Wa(u,p.historyIndex),p),_=Rp(f,{schema:i.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let y=(a.located?await ag(a.located,i,u):null)?.raw??null,g=C(n.author,i.author_default),v=await Ae(o,c,i.locks.ttl_seconds,g,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:b,existingItemPath:k}=await PT({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:m,currentItemRawBeforeLock:y,history:u}),T="toon",O=NT(b,u),L=LT({document:O.document,author:g,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),$=xT(O.document,_),K=await vr({pmRoot:o,settings:i,operation:"restore",author:g,before:O.document,after:_});await Ho({pm_root:o,operation:"restore",before:O.document,after:_,changed_fields:$,sdk:vi({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let J=He(_,{format:T,schema:i.schema}),z=dt(o,_.metadata.type,c,T,s.type_to_folder),ue=await Ft(o,g),oe=[];try{await te(z,J),k&&z!==k&&await Kc.rm(k);let Xe=Le({nowIso:S(),author:g,op:"restore",before:O.document,after:_,message:n.message,context:K.decisions.length===0?void 0:{workflow_policies:K.decisions}});try{await Pt(a.historyPath,Xe)}catch(tr){throw await $T({existingItemPath:k,resolvedOriginalRaw:O.originalRaw,restoredItemPath:z}),tr}oe=await Mt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:z,previousItemPath:k??void 0,document:_})}finally{await ue()}let Be=await FT({restoredItemPath:z,historyPath:a.historyPath,before:O.document,after:_});Cn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:O.document.metadata.status,status:_.metadata.status,previous:Qt(O.document.metadata,$),current:Qt(_.metadata,$),changed_fields:$});let j=u[p.historyIndex],le=Fn(u,!0);return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:le===null?null:le+p.historyIndex+1,entry_ts:j.ts,entry_op:j.op},changed_fields:$,warnings:[...K.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...L,...oe,...Be]}}finally{await v()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aec6f8e2-5fd0-53f3-8262-c6b49741ff96")}catch{}})();var dg=1,zc="close-many",MT=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function DT(e,t){return Ir(e,t,{includePagination:!1})}function UT(e,t){return Ir(e,t)}function GT(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 jT(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 qT(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 KT(e,t){let n=F(t.schema),r=x(t,R()),o=await fe(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,s=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(s.set(a.id,a.parent),re(a.status,n)))continue;let c=i.get(a.parent);c?c.push(a.id):i.set(a.parent,[a.id])}for(let a of i.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:i,parentByChild:s}}function lg(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),s=[],a=new Set,c=!1;for(;i!==void 0&&!a.has(i);){let m=n?.get(i);if(m!==void 0){o+=m+1;break}a.add(i),s.push(i),o+=1,i=t.get(i)}if(i!==void 0&&a.has(i)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of s.entries())n?.set(u,o-m-1)}return o}async function zT(e){let t=await ii(e.pmRoot,zc,e.rollbackId,dg),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await si(t.items,(o,i)=>sn(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 BT(e,t,n,r,o){return e.map(i=>{let s=(t.get(i.id)??[]).filter(c=>!n.has(c)),a=!mg(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...s.length>0?{active_child_ids:s}:{}}})}async function HT(e){let t=await oi(e.pmRoot,zc,e.checkpointId,{schema_version:dg,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 VT(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 vt(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:En(o)})}}return{rows:t,closedIds:n}}function WT(e){return typeof e.rollback=="string"?e.rollback:void 0}function YT(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(UT(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function JT(e){if(!DT(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${MT}). Refusing to match every item.`,d.USAGE)}function XT(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=lg(o.id,t,n)-lg(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function mg(e,t,n){return n||!re(e.status,t)}function QT(e,t,n){return new Set(e.filter(r=>mg(r,t,n)).map(r=>r.id))}async function ZT(e){JT(e.options);let t=F(e.settings.schema),n=qT(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ht(e.options.status,jT(e.options.list),e.global),{childrenByParent:i,parentByChild:s}=await KT(e.pmRoot,e.settings),a=XT(o.items,s),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,u=new Set(m.map(f=>f.id)),p=QT(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:BT(a,i,p,t,r)}}function eC(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 tC(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 HT({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 ug(e,t){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=e.dryRun===!0,i=WT(e);if(GT(e.list),i!==void 0)return YT(e,i),zT({pmRoot:n,rollbackId:i,options:e,global:t});let s=await ZT({pmRoot:n,settings:r,options:e,global:t});if(o)return eC(s);let a=new Set(s.planRows.filter(v=>v.action==="close").map(v=>v.id)),c=S(),m=ri(zc,c),u=await tC({context:s,options:e,closableIds:a,checkpointId:m,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:s.validateCloseMode,force:s.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await VT({matched:s.matched,closableIds:a,reason:s.reason,closeOptions:p,global:t}),h=f.filter(v=>v.status==="closed").length,y=f.filter(v=>v.status==="skipped").length,g=f.filter(v=>v.status==="failed").length;return{...en({applied:h,skipped:y,failed:g,unmatched:s.unmatchedIds?.length??0}),mode:"apply",matched_count:s.matched.length,dry_run:!1,...s.reason!==void 0?{reason:s.reason}:{},filters:s.listed.filters,...s.validateCloseMode?{validate_close:s.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:h,skipped_count:y,failed_count:g,rows:f,ids:_,...s.unmatchedIds!==void 0?{unmatched_ids:s.unmatchedIds,unmatched_count:s.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]="64b269aa-d285-53bb-8949-b75bed767479")}catch{}})();function nC(e,t){return[...new Set([...io.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function rC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Bc(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),i=x(o,R()),s=await q(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await _t(r,e,o.id_prefix,i.type_to_folder);let a=await se(s,{schema:o.schema}),c=a.document.metadata,m=S(),u=C(t.author,o.author_default),p=await gr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=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:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=Tt(R()),g=tt({metadata:h,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),v=await jn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[s.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=nC(g.metadata,g.body),k=dt(r,g.metadata.type,p,o.item_format,i.type_to_folder),T=Ze(r,p),O=await Ae(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),L={metadata:{},body:""},$,K;try{let J=await Ft(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await jn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[s.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let z=await q(r,p,o.id_prefix,o.item_format,i.type_to_folder);if(z)throw new l(`Cannot copy to ${p}: 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 ${p} already exists at ${z.itemPath}.`,recovery:{suggested_retry:`pm copy ${s.id}`}});await te(k,He(g,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let ue=Le({nowIso:m,author:u,op:"create",before:L,after:g,message:rC(s.id,t.message)});await Pt(T,ue)}catch(ue){throw await Sn(k),ue}K=await Mt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:k,document:g})}finally{await J()}$=[...await Y({path:k,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:L,after:g,changed_fields:b}),...await Y({path:T,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:L,after:g,changed_fields:b})],Cn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Qt(g.metadata,b),changed_fields:b})}finally{await O()}return{source_id:s.id,item:structuredClone(g.metadata),changed_fields:b,warnings:[...Ii(v),...K,...$],...v===void 0?{}:{similarity_advisory:v}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4db3d1b3-68f3-5f74-b6f0-9847b3b00fc0")}catch{}})();var oC="hierarchy-integrity";async function Vi(e){let t=e.required?await Ae(e.pmRoot,oC,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]="c45ead8e-c9ed-5b59-84e5-b8e077e84010")}catch{}})();function Wi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Yi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ji(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(oo.includes(t))return t;let n=pe(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 Xi(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]="add1928e-08d1-5ead-9a4e-0f1a9b6580fc")}catch{}})();var iC=new Set(["none","null"]);function Qi(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function We(e){return e===void 0?!1:iC.has(e.trim().toLowerCase())}function Zi(e,t,n){if(!We(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Re(e,t,n){if(!e||e.length===0||!e.some(i=>We(i)))return;let o=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${o}`.trim(),d.USAGE)}function es(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(!o.some(a=>We(a)))continue;if(o.filter(a=>!We(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca230957-d5a6-5f20-94b5-e1eeca8ca714")}catch{}})();var sC=new Set(["event","meeting","reminder","milestone","decision","adr"]);function pg(e,t,n,r){if(sC.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Ko("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]="70971b2a-c025-50a8-918f-871fc8adfd2a")}catch{}})();var wt=["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"],aC=new Set(wt);function fg(e){return ai(e,wt)}function ts(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!aC.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[s]=i}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${wt.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]="7ea4de2f-42e2-5ef3-89b2-d15ba6eb252a")}catch{}})();var ln=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Er,uf,"FORCE_COLOR"]),os=/^[A-Za-z_][A-Za-z0-9_]*$/,cn=["schema","tracker","auto","none"],_g=["source","isolated","snapshot"];function Mr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let 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 s=o.slice(0,i).trim(),a=o.slice(i+1);if(!os.test(s))throw new l(`${t} env_set key "${s}" is invalid`,d.USAGE);if(ln.has(s.toUpperCase()))throw new l(`${t} env_set key "${s}" is reserved for sandbox safety`,d.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function Dr(e,t){if(!e)return;let n=Dn(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(!os.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 is(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 ss(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(_g.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${_g.join(", ")}`,d.USAGE)}function mn(e){if(!e)return;let t=Dn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Hn(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 as(e,t){if(!e)return;let n=pe(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 cs(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 s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function ls(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 s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${s}" must be numeric`,d.USAGE);r[s]=c}return Object.keys(r).length>0?r:void 0}var cC=new Set(wt);function ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!cC.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw t(`provides key "${o}" more than once after case normalization`);n[s]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${wt.join(", ")}.`);return n}function an(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 ns(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(s=>typeof s!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(s=>s.length>0);return i.length>0?i:void 0}function hg(e,t,n){let r=ns(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 rs(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 dC(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:rs(n,"timeout_seconds",t),i=r===void 0?void 0:rs(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 s=o??i;if(!Number.isInteger(s)||s<=0)throw t("timeout_seconds must be a positive integer");return s}function mC(e,t){let n=an(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 uC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!ds(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(!os.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 pC(e,t){let n=ns(e,"env_clear",t);if(n){for(let r of n){if(!os.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 fC(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 _C(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=rs(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 hC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!ds(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 gC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!ds(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]=rs(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function yC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!ds(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${wt.join(", ")}.`);let o=lC(e,r),i=an(o,"command",r),s=an(o,"cmd",r);if(i!==void 0&&s!==void 0&&i!==s)throw r("command and cmd must match when both are provided");let a=i??s;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=an(o,"path",r),m=an(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 u=dn(an(o,"workspace_context_mode",r),`${n} ${t}`),p=an(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:mC(o,r),timeout_seconds:dC(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:uC(o,r),env_clear:pC(o,r),shared_host_safe:fC(o,"shared_host_safe",r),assert_stdout_contains:ns(o,"assert_stdout_contains",r),assert_stdout_regex:hg(o,"assert_stdout_regex",r),assert_stderr_contains:ns(o,"assert_stderr_contains",r),assert_stderr_regex:hg(o,"assert_stderr_regex",r),assert_stdout_min_lines:_C(o,r),assert_json_field_equals:hC(o,r),assert_json_field_gte:gC(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function gg(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,s)=>yC(i,o.length>1?`entry ${s+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]="0562fd00-217b-5e1f-8004-df4574f8b796")}catch{}})();var Hc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Vc=[{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"}],yg=[...Hc,...Vc],ms=[{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 us(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(We(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let 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 ps(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 s=new Set;if(typeof i.key=="string"&&i.key.length>0&&s.add(i.key.toLowerCase()),typeof i.metadata_key=="string"&&i.metadata_key.length>0&&s.add(i.metadata_key.toLowerCase()),typeof i.cli_flag=="string"&&i.cli_flag.length>0&&(s.add(i.cli_flag.replaceAll("-","_").toLowerCase()),s.add(i.cli_flag.toLowerCase())),Array.isArray(i.cli_aliases))for(let a of i.cli_aliases)typeof a!="string"||a.length===0||(s.add(a.replaceAll("-","_").toLowerCase()),s.add(a.toLowerCase()));if(s.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]="49f970c3-e408-52d5-bb4d-8cea0c7f8ef4")}catch{}})();function wg(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 Wc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Oe(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE,{field:r,required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var bg=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function vC(e,t){return t==="defined"?e!==void 0:!!e}function vg(e,t,n){if(!vC(e,n))return;let r=pe(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function wC(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 bC(e){return Array.from(new Set(Wc(e).map(t=>Oe(t.toLowerCase(),jd,"event weekday")))).sort((t,n)=>aa(t)-aa(n))}function kC(e){return Array.from(new Set(Wc(e).map(t=>{let n=pe(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 SC(e,t){return Array.from(new Set(Wc(e).map(n=>ie(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function kg(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),s=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,i,s,a,c,m,u].some(k=>k!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=Oe(o.toLowerCase(),Gd,"event recurrence frequency"),_=vg(i,"recur_interval",r),h=vg(s,"recur_count",r),y=wC(a,t,n),g=bC(c),v=kC(m),b=SC(u,n);return{freq:f,interval:_,count:h,until:y,by_weekday:g.length>0?g:void 0,by_month_day:v.length>0?v:void 0,exdates:b.length>0?b: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]="e2e87672-508a-5aef-b728-42e40544cf3c")}catch{}})();function Ur(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Gr(e,t,n=Dt()){for(let r of t??[])try{Bd(e,r.id,r.kind,n)}catch(o){throw new l(En(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Sg(e,t){return(await se(e,{schema:t})).document.metadata.created_at}async function EC(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Sg(n,t.schema)}function AC(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 TC(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 Sg(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await EC(o,e.context);if(i!==void 0)for(let s of t){let a=r.get(s.id),c=Date.parse(i),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw AC({holder:o,dependency:s,sourceCreatedAt:i,targetCreatedAt:a,registry:e.registry})}}}async function un(e){let t=e.registry??Dt(),n=(e.dependencies??[]).filter(s=>!Wu(s.source_kind)),r=[...new Set(n.map(s=>s.id))],o=await Promise.all(r.map(async s=>({target:s,located:await q(e.pmRoot,s,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:s})=>s===null).map(({target:s})=>s).sort((s,a)=>s<a?-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 TC({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(s=>`dependency_target_unresolved:${s}`)}(function(){try{var e=typeof window<"u"?window:typeof 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 CC={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 IC(e){return CC[e]}function Yc(e){return IC(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]="7bbd7a9a-052b-506d-8d63-6ae512556bde")}catch{}})();var Eg="--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.",RC="--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).",OC=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,xC=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Tg=1e3,Jc=60*Tg,PC=60*Jc;function Ag(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 NC(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=OC.exec(r);if(i){let c=i[1]==="-"?-1:1,m=Number.parseInt(i[2],10)*c;return Ag(n.getTime()+m*Jc,r)}let s=xC.exec(r);if(s){let[,c,m,u,p]=s;if(m||u||p){let _=c==="-"?-1:1,h=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),g=Number.parseInt(p??"0",10),v=h*PC+y*Jc+g*Tg;return Ag(n.getTime()+_*v,r)}}let a=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return ie(a,n,"event.duration")}function Cg(e,t,n,r){if(t&&n)throw new l(RC,d.USAGE);if(n){let i=NC(e,n);if(i<e)throw new l(Eg,d.USAGE);return i===e?void 0:i}if(!t)return;let o=ie(t,r,"event.end");if(o<e)throw new l(Eg,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]="dfce9924-8453-5ded-a5df-47477caa9fe7")}catch{}})();var LC=["at","date","text","title"],$C=["start","date","end","duration","title","description","location","timezone","all_day",...bg],FC=["key","value"];function Ig(e,t){return t==="trimmed"?e?.trim():e}function MC(e,t){return t==="defined"?e!==void 0:!!e}function fs(e,t,n){return e.map(r=>{let o=de(r,"--reminder");Ve(o,"--reminder",LC);let i=Ig(o.at??o.date,n.valueMode),s=Ig(o.text??o.title,n.valueMode);if(!i||!s)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let a=s.trim();if(!a)throw new l("--reminder text must not be empty",d.USAGE);return{at:ie(i,t,"reminder.at"),text:a}})}function _s(e,t,n){return e.map(r=>{let o=de(r,"--event");Ve(o,"--event",$C);let i=(o.start??o.date)?.trim();if(!i)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let s=ie(i,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=Cg(s,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,h=u?.trim(),y=p?.trim(),g=f?.trim(),v=_?.trim(),b=[["title",u,h],["description",p,y],["location",f,g],["timezone",_,v]];for(let[L,$,K]of b)if($!==void 0&&!K)throw new l(`--event ${L} must not be empty`,d.USAGE);let k=o.all_day?.trim(),T=kg(o,s,t,n.recurrenceEmptyNumericGuard),O=MC(k,n.allDayEmptyGuard)?wg(k,"--event all_day"):void 0;return{start_at:s,end_at:m,title:h,description:y,location:g,all_day:O,timezone:v,recurrence:T}})}function hs(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(`
20
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=de(r,"--type-option");Ve(a,"--type-option",FC),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,m).trim(),i=r.slice(m+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]="ad3f992c-db2e-5276-a8ae-5d5d4ec8ae68")}catch{}})();var DC=["strict","progressive"],UC=["lightweight"],Pg=new Set(["Reminder","Meeting","Event"]),GC=new Set(["author","created_at","text"]),Qc=[...yg,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...ms],jC=(()=>{let e=new Map;for(let t of Qc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),gs=new Map(Qc.map(e=>[e.optionKey,e.canonical])),qC=Qc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function KC(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 zC(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 Xc(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 BC=Qi();function Ng(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};We(t.template)&&(t.template=void 0);let r=new Set([...gs.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!We(i))continue;let s=o==="rank"?"order":gs.get(o)??o;n(s),t[o]=void 0}return Ce(e,es(t,BC))}function ve(e){if(e!==void 0)return e}function HC(e,t){return us({raw:e,supportedFields:qC,resolveDefinition:n=>jC.get(n)??ps(n,"create",t)})}var Rg=["id","kind","type","author","created_at","source_kind"],ys=["path","scope","note"];function VC(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let s=i.trim(),a=vs(s,Rg);Ur(s,a);let c=a?de(i,"--dep"):{id:s,kind:"related"};a&&Ve(c,"--dep",Rg);let m=ve(c.id),u=WC(ve(c.kind??c.type));if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(m.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(ve(c.source_kind)),f=ve(c.author);return{id:kr(m,n,p),kind:Oe(u,Vt,"dependency kind","kind"),created_at:Xc(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function WC(e){return typeof e=="string"?co(e)??e.trim():e}function vs(e,t){return ai(e,t)?!0:di(e)}function fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Re(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(s=>{let a=s.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=de(s,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!GC.has(f)).length>0)return{created_at:Xc(m.created_at,n),author:ve(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Xc(m.created_at,n),author:ve(m.author)??r,text:p}}),explicitEmpty:!1})}function Zc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=vs(r,ys);Ba(r,"--file","file path",o);let i=o?de(n,"--file"):{path:r};if(o&&Ve(i,"--file",ys),!i.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:i.path,scope:Oe(i.scope??"project",ct,"file scope"),note:ve(i.note)}}),explicitEmpty:!1})}function el(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=vs(r,wt);Ba(r,"--test","test command",o);let i=o?ts(de(n,"--test"),"--test"):{command:r},s=ve(i.command),a=ve(i.path);if(!s)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let c=ve(i.timeout_seconds),m=ve(i.timeout);if(c&&m&&c!==m)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let u=c??m;return{command:s,path:a,scope:Oe(i.scope??"project",ct,"test scope"),timeout_seconds:u?pe(u,"timeout_seconds"):void 0,pm_context_mode:ss(i.pm_context_mode,"--test"),workspace_context_mode:dn(i.workspace_context_mode,"--test"),env_set:Mr(i.env_set,"--test"),env_clear:Dr(i.env_clear,"--test"),shared_host_safe:is(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:mn(i.assert_stdout_contains),assert_stdout_regex:Hn(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:mn(i.assert_stderr_contains),assert_stderr_regex:Hn(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:as(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:cs(i.assert_json_field_equals,"--test"),assert_json_field_gte:ls(i.assert_json_field_gte,"--test"),note:ve(i.note)}}),explicitEmpty:!1})}function tl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=vs(r,ys),i=o?de(n,"--doc"):{path:r};if(o&&Ve(i,"--doc",ys),!i.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:i.path,scope:Oe(i.scope??"project",ct,"doc scope"),note:ve(i.note)}}),explicitEmpty:!1})}function YC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--reminder","Use --clear-reminders to clear reminders."),{values:fs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function JC(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--event","Use --clear-events to clear linked events."),{values:_s(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function XC(e,t,n,r=[]){let o=[...io.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 QC(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Og(e,t,n){let r=rr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function ZC(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 Lg(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 eI(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Og(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Og(r,e.name,"required_create_repeatables"));return n}function tI(e,t,n,r){for(let o of e)if(!(!Lg(t,o)&&!n.has(o)))throw new l(`Option ${Ee("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function nI(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Yc(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Ee("create",i)))].sort((i,s)=>i.localeCompare(s));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function rI(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:hs(e),explicitEmpty:!1})}async function oI(e){return await mi(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 iI(e){return ft(e)?await oI(e):e}function sI(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: ${DC.join(", ")}`,d.USAGE)}function aI(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: ${UC.join(", ")}`,d.USAGE)}function cI(e,t,n){let r=sI(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 lI(e,t,n,r){let o=e.name,i=ZC(t),s=eI(e,n),a=An(e,"create",s);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);tI(a.disabled,i,r,o),nI(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Yc(u)?!0:Lg(i,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>Ee("create",u)))].sort((u,p)=>u.localeCompare(p))}var $g=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function dI(e,t){let n=[];for(let r of e){let o=r.match($g);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function mI(e,t){return e.filter(n=>{let r=n.match($g);return!r||r[2]!==t})}function uI(e,t,n,r){let o=mI(e,t);if(o.length===0)return;let i=Fg(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 pI(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function fI(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function Fg(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"],s=[...new Set([...i,...t])],a=new Set(["--title","--description","--type"]);for(let c of s)a.has(c)||(o.push(...fI(c,e.name,r)),a.add(c));for(let c of n){let m=pI(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function nl(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 _I(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 hI(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function gI(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||hI(t.command)==="templates show"):!1}function yI(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(s=>typeof s=="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 vI(e,t,n){if(!gI())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Vo({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 yI(r.result,e)}function H(e,t,n){return e.has(t)||n===void 0?void 0:ve(n)}function pn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var wI=new Set(["milestone","meeting","reminder","event"]);function Mg(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,s=r!==void 0&&r.length>0;return wI.has(e.toLowerCase())&&!o&&!i&&!s}function bI(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`),Mg(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 kI(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Zo(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function SI(e,t,n,r,o,i){let s=bi(_i(o),t.id_prefix);if(Jo(s))return{parent:s,warnings:[]};if(gi(r,s,t.id_prefix),await q(e,s,t.id_prefix,t.item_format,n.type_to_folder))return{parent:s,warnings:[]};let c=Ke(s,t.id_prefix);return{parent:s,warnings:hi(c,i).warnings}}async function EI(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await SI(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function AI(e){if(e.explicitId===void 0)return gr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||jp(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=Ke(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function xg(e,t,n,r,o){let i=H(e,t,n);if(i===void 0)return{value:void 0,warnings:[]};let s=yi(r,i,o);return{value:s.value,warnings:s.warnings}}async function TI(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:s,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(i===void 0)return{dependencyValues:u,status:s};let p=Ke(i,n.id_prefix),f=await q(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:s};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:s};let h=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??o.open_status;return{dependencyValues:u,status:h}}function CI(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&be(o,n)){e.type=o;return}be("Task",n)&&(e.type="Task")}function II(e,t){return e.options.filter(n=>rr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function RI(e,t,n,r,o){let i=e,s=[];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 y=await vI(h,t,n);i=Ng(_I(y,i))}if(i.type===void 0&&CI(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=be(i.type,o);if(!a){let h=Kp(i.type),y=h?be(h,o):void 0;if(y)s.push(`type_coercion:${i.type.trim()}:${y}`),i.type=y,a=y;else throw new l(Ot(i.type,o.types,xt(n,r.schema)),d.USAGE)}let c=lo(a,o);if(!c)throw new l(`Invalid type value "${i.type}"`,d.USAGE);let m=c.name,u=II(c,i),p=u.map(h=>`${h.key}=${String(i[h.key])}`);if(p.length>0){i.typeOption=[...p,...i.typeOption??[]];for(let h of u)delete i[h.key]}let f=aI(i.schedulePreset);if(f!==void 0&&!Pg.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=cI(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:s}}function OI(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 xI(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=gs.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ee("create",r)}`,d.USAGE)}}function PI(e){let t=(n,r)=>{let o=gs.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Zi(n,Ee("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 NI(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 LI={"--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 $I(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:s,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let y=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${y}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),u=[Fg(n,r,o,i),...m.map(h=>h.example)].join(" "),p=[`Run "pm create --help --type ${s}" 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 '+s+").")];a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Pg.has(s)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let y=h.split(" ",1)[0],g=LI[y];return g?[g]:[]}))];f.length>0&&p.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 "${s}"`:`Missing required options ${t.join(", ")} for type "${s}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${s}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${s} ${h} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function FI(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?Nt(t.tags):[];return Nn(n,t.addTags)}function MI(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=pn(e,"order",n,o=>pe(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function DI(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 s=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:s,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:jc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:s,warnings:[]}}async function UI(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:s,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=dt(t,n,r,o.item_format,i.type_to_folder),g=Ze(t,r),v=Dt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(L=>v.resolve(L.kind)?.hierarchy),k=await Vi({pmRoot:t,author:s,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,O=[];try{let L=await Ae(t,r,o.locks.ttl_seconds,s,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let $=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await fe(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0;if(await q(t,r,o.id_prefix,o.item_format,i.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if($){let oe=F(o.schema);ki($,[...$,c.metadata],r,Be=>re(Be,oe),v)}let J=await vr({pmRoot:t,settings:o,operation:"create",author:s,before:null,after:c});await Ho({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:vi({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let z=await Ft(t,s,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),ue=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await jn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await te(y,He(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let oe=Le({nowIso:f,author:s,op:"create",before:m,after:c,message:u,context:J.decisions.length===0?void 0:{workflow_policies:J.decisions}});await Pt(g,oe)}catch(oe){throw await Sn(y),oe}T&&(await k(),T=!1),ue=await Mt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await z()}O=[...J.warnings,...$?Fi($,[...$,c.metadata],r):[],...ue,...await Y({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await Y({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],Cn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Qt(c.metadata,p),changed_fields:p})}finally{await L()}}finally{T&&await k()}return O}async function jt(e,t){let n=Ng(await iI(e)),r=E(process.cwd(),t.path);await I(r);let o=await A(r),i=F(o.schema),s=et(o.schema),a=x(o,R()),c=await RI(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=HC(n.unset,s),{explicitUnsets:_,clearOptionKeys:h}=OI(n,f);xI(n,f),PI(n);let y=lI(m,n,p,h),g=S(),v=C(ve(n.author),o.author_default),b=VC(n.dep,g,o.id_prefix,v),k=fn("--comment",n.comment,g,v),T=fn("--note",n.note,g,v),O=fn("--learning",n.learning,g,v),L=Zc(n.file),$=el(n.test);$.values=await Kn($.values,v,g);let K=tl(n.doc),J=YC(n.reminder,g),z=JC(n.event,g),ue=rI(n.typeOption),oe=or(u,ue.values,a),Be=R(),j=Tt(Be),le=so(n.field,Be),Xe=pp(n,s,u),tr=new Set(Xe.missing_required_flags),Js=s.definitions.filter(W=>tr.has(`--${W.cli_flag}`));NI(le,Xe,f);let nr=dI(oe.errors,u),Bt=nr.map(W=>`--type-option ${W}=<value>`),kd=[...new Set([...y,...Bt,...Xe.missing_required_flags])].sort((W,ia)=>W.localeCompare(ia));$I({combinedMissingFlags:kd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:nr,openStatus:i.open_status,type:u,createMode:p,missingRequiredRuntimeFields:Js}),uI(oe.errors,u,m,i);let Ne=await AI({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),St=n.status!==void 0?KC(n.status,i):zC(m,i),Xs=n.priority!==void 0?$n(n.priority):2,P=f.metadataKeys,je=FI(P,n),at=pn(P,"deadline",n.deadline,W=>ie(W,new Date(g),"deadline")),Qr=pn(P,"estimated_minutes",n.estimatedMinutes,W=>Ln(W,"estimated-minutes")),Et=H(P,"acceptance_criteria",n.acceptanceCriteria),Qs=H(P,"definition_of_ready",n.definitionOfReady),Qe=MI(P,n),Zs=H(P,"goal",n.goal),Zr=H(P,"objective",n.objective),ob=H(P,"value",n.value),ib=H(P,"impact",n.impact),sb=H(P,"outcome",n.outcome),ab=H(P,"why_now",n.whyNow),cb=H(P,"assignee",n.assignee),lb=P.has("author")?void 0:ve(n.author)??v,db=H(P,"parent",n.parent),Sd=await kI(db,n,P,r),ea=Sd.parent,mb=Sd.parentSource,ub=H(P,"reviewer",n.reviewer),pb=pn(P,"risk",n.risk,W=>Oe(Wi(W),bn,"risk")),fb=pn(P,"confidence",n.confidence,W=>Ji(W)),_b=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Ed=o.validation.sprint_release_format,Ht=[...c.warnings,...bI(u,Ne,at,J.values,z.values)],Ad=await EI({itemId:Ne,parent:ea,pmRoot:r,settings:o,typeRegistry:a,policy:_b});ea=Ad.parent,Ht.push(...Ad.warnings);let Td=xg(P,"sprint",n.sprint,"sprint",Ed),hb=Td.value;Ht.push(...Td.warnings);let Cd=xg(P,"release",n.release,"release",Ed),gb=Cd.value;Ht.push(...Cd.warnings);let Id=H(P,"blocked_by",n.blockedBy),Rd=await TI({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:i,blockedBy:Id,dependencyValues:b.values,status:St,statusExplicit:n.status!==void 0,nowValue:g,author:v}),ta=Rd.dependencyValues;Gr(Ne,ta),Ht.push(...await un({pmRoot:r,dependencies:ta,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ne,createdAt:g}],schema:o.schema})),St=Rd.status;let yb=H(P,"blocked_reason",n.blockedReason),vb=H(P,"unblock_note",n.unblockNote),wb=H(P,"reporter",n.reporter),bb=pn(P,"severity",n.severity,W=>Oe(Yi(W),kn,"severity")),kb=H(P,"environment",n.environment),Sb=H(P,"repro_steps",n.reproSteps),Od=H(P,"resolution",n.resolution),Eb=H(P,"expected_result",n.expectedResult),Ab=H(P,"actual_result",n.actualResult),Tb=H(P,"affected_version",n.affectedVersion),Cb=H(P,"fixed_version",n.fixedVersion),Ib=H(P,"component",n.component),Rb=pn(P,"regression",n.regression,W=>Xi(W)),Ob=H(P,"customer_impact",n.customerImpact),na=nl(n.title,"--title"),ra=n.description??"",eo=n.body??"",xd=await jn({title:na,description:ra,body:eo},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Ht.push(...Ii(xd));let oa=DI(St,i,o,n,Od,g),xb=oa.closeReason,Pb=St===i.close_status?g:void 0,Nb=oa.completedAt;Ht.push(...oa.warnings);let to=Ua({id:Ne,title:na,description:ra,type:u,type_options:oe.normalized,status:St,closed_at:Pb,completed_at:Nb,close_reason:xb,priority:Xs,tags:je,created_at:g,updated_at:g,deadline:at,assignee:cb,author:lb,estimated_minutes:Qr,acceptance_criteria:Et,definition_of_ready:Qs,order:Qe,goal:Zs,objective:Zr,value:ob,impact:ib,outcome:sb,why_now:ab,parent:ea,reviewer:ub,risk:pb,confidence:fb,sprint:hb,release:gb,blocked_by:Id,blocked_reason:yb,unblock_note:vb,reporter:wb,severity:bb,environment:kb,repro_steps:Sb,resolution:Od,expected_result:Eb,actual_result:Ab,affected_version:Tb,fixed_version:Cb,component:Ib,regression:Rb,customer_impact:Ob,dependencies:ta,comments:k.values,notes:T.values,learnings:O.values,files:L.values,tests:$.values,docs:K.values,reminders:J.values,events:z.values,...le,...Xe.values});try{ao(to,Be)}catch(W){throw new l(W instanceof Error?W.message:"Invalid extension item field values",d.USAGE)}let Lb=tt({metadata:to,body:eo},{schema:o.schema,extensionFieldNames:j}),$b={metadata:{},body:""},Pd=[..._].sort((W,ia)=>W.localeCompare(ia)),Fb=QC(n.message,Pd),Nd=XC(to,eo,Pd,[...Object.keys(le),...Object.keys(Xe.values??{})]),Mb=await UI({pmRoot:r,type:u,id:Ne,settings:o,typeRegistry:a,author:v,extensionFieldNames:j,afterDocument:Lb,beforeDocument:$b,historyMessage:Fb,changedFields:Nd,nowValue:g,similarityCandidate:{title:na,description:ra,body:eo},allowDuplicate:n.allowDuplicate}),Ld=structuredClone(to);p==="strict"&&_.has("dependencies")&&(Ld.dependencies=[]);let Db=pg(Ne,u,St,i);return Mg(u,at,J.values,z.values)&&Vu(`[pm] warning: ${u} '${Ne}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ne} --deadline <ISO>' or 'pm update ${Ne} --event "start=<ISO>,end=<ISO>"'.`),{item:Ld,changed_fields:Nd,warnings:[...Ht,...Mb],...Object.fromEntries([["parent_source",mb],["next_transition",Db],["similarity_advisory",xd]].filter(W=>W[1]!==void 0))}}import ws 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]="eef2ba25-bbdb-5c06-9f90-1cf485e98497")}catch{}})();async function rl(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),s=await Jp({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),a=s.targetPath?ws.relative(r,s.targetPath).split(ws.sep).join("/"):void 0;return{item:s.item,changed_fields:s.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:s.item.status,...a?{target_path:a}:{},history_retained:ws.relative(r,Ze(r,s.item.id)).split(ws.sep).join("/"),tombstone_retention:"retain_append_only",warnings:s.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]="8023e71b-f733-572c-bdc0-e9b8f481232c")}catch{}})();async function GI(e){await I(e)}async function ol(e,t,n){let r=E(process.cwd(),n.path);if(await GI(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),f=xn(C(void 0,p.author_default));return await up(r),await Mi({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Zo(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 f=await jI(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let i=await A(r),s=x(i,R()),a=await q(r,e,i.id_prefix,i.item_format,s.type_to_folder);if(!a)throw await _t(r,e,i.id_prefix,s.type_to_folder);let c=Ke(a.id,i.id_prefix),m=await se(a,{schema:i.schema}),u=Dg(m.document.metadata.title);return await mp(r,c),await Mi({pmRoot:r,settings:i,principal:xn(C(void 0,i.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function jI(e,t){let n=await A(e),r=x(n,R()),o=await q(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await se(o,{schema:n.schema});return Dg(i.document.metadata.title)}function Dg(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 bs(e){return Ko("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]="c088edd0-4756-5c13-abac-468cf6a008df")}catch{}})();var cl=[...Hc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Vc,...ms],qI=(()=>{let e=new Map;for(let t of cl)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ks=new Map(cl.map(e=>[e.optionKey,e.canonical])),KI=cl.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),zI=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),BI=Qi({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Hg(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([...ks.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!We(i))continue;let s=o==="rank"?"order":ks.get(o)??o;n(s),t[o]=void 0}return Ce(e,es(t,BI))}function Vg(e,t,n=[]){return us({raw:e,supportedFields:KI,resolveDefinition:r=>{let o=n.find(s=>{let a=s.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return qI.get(r)??ps(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var Ug=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 Gg(e){let t=e.disallowedFlags.flatMap(r=>{let o=Ug.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=Ug.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 HI(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,u)=>{c&&u.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 Gg({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 s=[];i(t.status!==void 0,"--status",s),i(t.closeReason!==void 0,"--close-reason",s),i(t.assignee!==void 0,"--assignee",s),i(t.parent!==void 0,"--parent",s),i(t.blockedBy!==void 0,"--blocked-by",s),i(t.blockedReason!==void 0,"--blocked-reason",s),i(t.unblockNote!==void 0,"--unblock-note",s),i(t.dep!==void 0,"--dep",s),i(t.depRemove!==void 0,"--dep-remove",s),i(t.replaceDeps===!0,"--replace-deps",s),i(t.replaceTests===!0,"--replace-tests",s),i(t.replaceFiles===!0,"--replace-files",s),i(t.replaceDocs===!0,"--replace-docs",s),i(t.note!==void 0,"--note",s),i(t.learning!==void 0,"--learning",s),i(t.test!==void 0,"--test",s),i(t.reminder!==void 0,"--reminder",s),i(t.event!==void 0,"--event",s),i(t.clearDeps===!0,"--clear-deps",s),i(t.clearComments===!0,"--clear-comments",s),i(t.clearNotes===!0,"--clear-notes",s),i(t.clearLearnings===!0,"--clear-learnings",s),i(t.clearFiles===!0,"--clear-files",s),i(t.clearTests===!0,"--clear-tests",s),i(t.clearDocs===!0,"--clear-docs",s),i(t.clearReminders===!0,"--clear-reminders",s),i(t.clearEvents===!0,"--clear-events",s);let a=[...n].filter(c=>zI.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(s.push(...a),s.length>0)throw Gg({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: ${s.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:s})}function VI(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 WI(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Eu({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: ${Au(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function YI(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Wg(e)}function Wg(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 Vn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var JI=["id","kind","type","author","created_at","source_kind"],XI=["id","kind","type","author","created_at","source_kind"];function Yg(e){return e.startsWith("```")||e.includes(`
21
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:di(e)}function Jg(e){return typeof e=="string"?co(e)??e.trim():e}function Es(e,t,n,r){return e?(Re(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let s=i.trim(),a=Yg(s);Ur(s,a);let c=a?de(i,"--dep"):{id:s,kind:"related"};a&&Ve(c,"--dep",JI);let m=c.id?.trim(),u=Jg((c.kind??c.type)?.trim());if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(m.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=br(Vn(c.source_kind)),f=Vn(c.author);return{id:kr(m,t,p),kind:Oe(u,Vt,"dependency kind","kind"),created_at:YI(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function QI(e,t){return e?(Re(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=Yg(r);if(Ur(r,o,"--dep-remove"),o){let i=de(r,"--dep-remove");Ve(i,"--dep-remove",XI);let s=i.id?.trim();if(!s)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(s.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${s}"`,d.USAGE);let a=Jg(Vn(i.kind??i.type)),c=br(Vn(i.source_kind)),m=Vn(i.author),u=Vn(i.created_at);return{id:kr(s,t,c),kind:a?Oe(a,Vt,"dependency kind","kind"):void 0,source_kind:c,author:m,created_at:u?Wg(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:Ke(r,t)}})):[]}function Ss(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function ZI(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 eR(e,t,n,r){let o=[...e??[]],i=!1;if(t===void 0){let s=o.filter(a=>a.kind!=="blocked_by");return s.length!==o.length&&(o=s,i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(s=>s.kind==="blocked_by"&&s.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 tR(e,t,n,r,o,i){if(e===void 0||t)return{};let s=e.trim();if(s.length===0)return{};let a=await q(n,Ke(s,r),r,o,i);return a?{id:a.id}:{unresolved:s}}function nR(e,t,n,r,o){let i=eR(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 rR(e){return`${e.path}::${e.scope}`}function oR(e){return`${e.path}::${e.scope}`}function iR(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Xg(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 jg(e,t){let n=rr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function sR(e,t,n){let r=new Set,o=(i,s)=>{s&&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=Vg(e.unset,t,n);for(let s of i.optionKeys)o(s,!0)}return r}function aR(e,t,n,r,o){let i=lo(e,n);if(!i)throw new l(`Invalid type value "${e}"`,d.USAGE);let s=An(i,"update",[]);if(s.errors.length>0)throw new l(s.errors.join("; "),d.CONFLICT);let a=sR(t,r,o);for(let c of s.disabled)if(a.has(jg(c,e)))throw new l(`Option ${Ee("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of s.required)if(!a.has(jg(c,e)))throw new l(`Missing required option ${Ee("update",c)} for type "${e}"`,d.USAGE)}var cR=new Set(["order","rank"]),lR=_a.filter(e=>!cR.has(e)),Qg=["tags","closeReason",...lR],dR=["title","description","body","status","closeReason","completedAt","priority","type",..._a,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],mR=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ie(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Ln(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"}],uR=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Oe(Wi(e),bn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Ji(e)}],pR=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Oe(Yi(e),kn,"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=>Xi(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function al(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(`${Ee("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 fR(e){return Hg(await mi(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 ll(e){return ft(e)?await fR(e):Hg(e)}function _R(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 il(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 dl(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);il({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),il({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),il({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function hR(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 gR(e){let t={};for(let n of Qg)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function yR(e,t){let n=gR(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=ks.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Ee("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 vR(e){let t=(n,r)=>{let o=ks.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Zi(n,Ee("update",r),i)};for(let n of Qg)t(e[n],String(n));t(e.order??e.rank,"order"),Re(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Re(e.event,"--event","Use --clear-events to clear linked events.")}function wR(e,t){let n={};for(let r of dR)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 bR(e){let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await se(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function kR(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return fe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function SR(e){e.before&&ki(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),Dt())}function ER(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 AR(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=bi(_i(e.options.parent),e.settings.id_prefix);if(Jo(t))return{resolvedParentValue:t,warnings:[]};if(gi(e.id,t,e.settings.id_prefix),await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=Ke(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:hi(r,e.parentReferencePolicy).warnings}}function TR(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function CR(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await se(t,{schema:e.settings.schema}),r=e.options.type!==void 0?be(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=WI({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function IR(e){if(!e.fieldFlags.status||ee(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=Ce(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await it(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let i=await vt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),s=[...e.workflowTransitionWarnings,...r,...i.warnings,"auto_routed_from_update_to_close"];return{item:i.item,changed_fields:[...o,...i.changed_fields],warnings:s}}function RR(e,t,n,r){return t.title!==void 0&&(e.metadata.title=nl(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 OR=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function xR(e,t){for(let n of OR)e[n]!==void 0&&(delete e[n],t.push(n))}function PR(e,t,n,r,o){let i=VI(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)&&xR(e.metadata,o)}function NR(e,t,n,r){if(t.options.status!==void 0&&PR(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 LR(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 $R(e,t,n,r){NR(e,t,n,r),LR(e,t,n,r)}function FR(e,t,n){let r=be(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=$n(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=be(t.options.type,t.typeRegistry);if(!o)throw new l(Ot(t.options.type,t.typeRegistry.types,xt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return aR(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),MR(e,t,r,n),r}function MR(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=hs(t.options.typeOption??[]),s=or(n,i,t.typeRegistry);if(s.errors.length>0)throw new l(s.errors.join("; "),d.USAGE);e.metadata.type_options=s.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=or(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function DR(e,t){let n=new Set(t.map(o=>Ss(o))),r=new Set;return e.filter(o=>{if(!n.has(Ss(o)))return!0;let i=ZI(o);return r.has(i)?!1:(r.add(i),!0)})}function UR(e,t,n){let r=t.filter(o=>!e.some(i=>Xg(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 GR(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=DR(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>Ss(i)));for(let i of t.dependencyUpdates.additions){let s=Ss(i);o.has(s)||(r.push(i),o.add(s))}}t.dependencyRemovals.length>0&&(UR(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>Xg(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function jR(e,t,n){sl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),sl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),sl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function sl(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 qR(e,t,n){qg(e,"files",t.options.file,t.fileUpdates.values,rR,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),KR(e,t,n),qg(e,"docs",t.options.doc,t.docUpdates.values,oR,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function qg(e,t,n,r,o,i,s,a){if(!(n===void 0&&!s.has(t))){if(i)e.metadata[t]=r;else if(s.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function KR(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Kg(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Kg([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Kg(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=iR(r);n.has(o)||(t.push(r),n.add(o))}return t}function zR(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 s=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Nt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=li(Nn(s,r),o),n.changedFields.push("tags")}al(mR,t.options,n),HR(e,t,n.changedFields)}function BR(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=ci(Pn(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 s=i.criteria.join("; ");e.metadata.acceptance_criteria!==s&&(s===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=s,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function HR(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=pe(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function VR(e,t,n,r){WR(e,t,n.changedFields),YR(e,t,n.changedFields),al(uR,t.options,n),zg(e,t,"sprint",r,n.changedFields),zg(e,t,"release",r,n.changedFields),JR(e,t,n.changedFields),al(pR,t.options,n)}function WR(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 YR(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 zg(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=yi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function JR(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)&&nR(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function XR(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=fs(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=_s(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function QR(e,t,n){Bg(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Bg(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let s=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??s;throw new l(`Cannot combine --unset ${s} with --${c}`,d.USAGE)}qe(e[o],i)||(e[o]=i,n.push(o))}let r=so(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))qe(e[o],i)||(e[o]=i,n.push(o))}function Bg(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function ZR(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)||!qe(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 e0(e,t){ZR(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],s=RR(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};$R(e,t,s,o),FR(e,t,o),GR(e,t,o),jR(e,t,o),qR(e,t,o),zR(e,t,c),BR(e,t,c),VR(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"))&&Gr(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")),XR(e,t,o),QR(a,t,o);try{ao(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new l(p instanceof Error?p.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,u=[...new Set(o)].filter(p=>p==="body"?e.body!==r:!qe(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${Pn(n.acceptance_criteria).length}:${Pn(m.acceptance_criteria).length}`),{changedFields:u,warnings:i}}async function Zg(e,t,n,r={}){t=await ll(t);let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=F(i.schema),a=et(i.schema),c=R(),m=Tt(c),u=x(i,c),p=i.governance.workflow_enforcement??"off",f=p==="off"?[]:Su(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=Vg(t.unset,a,m),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);dl(t),hR({definitions:_R(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),HI(e,t,g),yR(t,h),vR(t);let v=C(t.author,i.author_default),b=new Date,k=b.toISOString(),T=Es(t.dep,i.id_prefix,k,v);Gr(e,T.additions);let O=await un({pmRoot:o,dependencies:T.additions,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:i.schema}),L=QI(t.depRemove,i.id_prefix),$=fn("--comment",t.comment,k,v),K=t.ownershipMetadataBypass===!0&&$.values?{...$,values:$.values.map(je=>({...je,author:v}))}:$,J=fn("--note",t.note,k,v),z=fn("--learning",t.learning,k,v),ue=Zc(t.file),oe=el(t.test);oe.values=await Kn(oe.values,v,k);let Be=tl(t.doc),j=[],le=await AR({id:e,options:t,unsetTargets:h,pmRoot:o,settings:i,typeRegistry:u,parentReferencePolicy:_}),Xe=await tR(t.blockedBy,g.has("blocked_by"),o,i.id_prefix,i.item_format,u.type_to_folder),tr=Xe.id,Js=[...le.warnings,...TR(Xe)],nr=ti(t,a,t.runtimeFieldCommands),Bt=wR(t,nr);if(!Object.values(Bt).some(Boolean))return bR({pmRoot:o,id:e,settings:i,typeRegistry:u});j.push(...await CR({options:t,fieldFlags:Bt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:s,typeRegistry:u,pmRoot:o,id:e,settings:i}));let Ne=await IR({options:t,fieldFlags:Bt,statusRegistry:s,workflowTransitionWarnings:j,global:n,id:e});if(Ne)return Ne;ER(t);let St=Dt(),Xs=Bt.parent&&!g.has("parent")||T.additions.some(je=>St.resolve(je.kind)?.hierarchy),P=await Vi({pmRoot:o,author:v,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:Xs});try{let je=await kR({fieldFlags:Bt,clearedMetadataKeys:g,pmRoot:o,settings:i,typeToFolder:u.type_to_folder}),at,Qr,Et=await Yp({pmRoot:o,settings:i,typeToFolder:u.type_to_folder,id:e,op:t0(t,r),author:v,message:t.message,resolveHistoryContext:()=>Qr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Qe){at=n0({document:Qe,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:s}),Qr=at?{recurrence:at}:void 0,je=je?.map(Zr=>Zr.id===Qe.metadata.id?structuredClone(Qe.metadata):Zr);let Zs=e0(Qe,{options:t,settings:i,typeRegistry:u,statusRegistry:s,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:g,dependencyUpdates:T,dependencyRemovals:L,commentUpdates:K,noteUpdates:J,learningUpdates:z,fileUpdates:ue,testUpdates:oe,docUpdates:Be,resolvedParentValue:le.resolvedParentValue,resolvedBlockedByDependencyId:tr,runtimeFieldUpdates:nr,nowValue:b,nowIso:k,author:v,pmRoot:o});return SR({before:je,document:Qe,statusRegistry:s}),Zs}});await P();let Qs=je?Fi(je,je.map(Qe=>Qe.id===Et.item.id?Et.item:Qe),Et.item.id):[];return{item:Et.item,changed_fields:Et.changedFields,warnings:[...j,...Js,...O,...Qs,...Et.warnings],...at===void 0?{}:{lifecycle_transition:at}}}finally{await P()}}function t0(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function n0(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(s=>{let a=o[s];return typeof a=="string"?[[s,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function it(e,t,n){return Zg(e,t,n)}async function ey(e,t,n,r){let o=await Zg(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]="cd0e532e-0f27-5786-8216-c17132f6e784")}catch{}})();async function ml(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),s=F((await A(i)).schema),a=s.open_status,c=bs(s),m=n.status??a,u=ee(m,s)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} 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([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await ey(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.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]="f366dd76-73b4-55c4-8c63-2913d0a0c380")}catch{}})();async function ty(e,t,n){return[...await Promise.resolve().then(()=>bp(Ze(e,t),t)).catch(()=>[])].reverse().find(i=>i.patch.some(s=>s.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]="f2901314-4044-5a91-ad72-6b4bebde16c2")}catch{}})();var ny="no_available_next_item";function ry(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function jr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=F(i.schema),a=C(r.author,i.author_default),c=xn(a),m=null,u=!1,p=[],f=await ae({pmRoot:o,settings:i,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,yu(_.metadata.status,s)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let T=await ty(o,_.metadata.id,y);throw new l(`Item ${_.metadata.id} is already ${T}. 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."]})}p.push(`claim_takeover:${m}->${a}`)}let b={assignee:a,claim_principal:c},k=["assignee","claim_principal"].filter(T=>_.metadata[T]!==b[T]);return Object.assign(_.metadata,b),{changedFields:k,warnings:p}}});return u||await uc({pmRoot:o,settings:i,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function oy(e,t,n={},r={}){let o=r0(n.maxAttempts),i=await A(E(process.cwd(),t.path)),s={...n,author:C(n.author,i.author_default)},a=await Rr({...r,callerAuthor:s.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return o0(c.slice(0,o),e,t,s)}function r0(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 o0(e,t,n,r={},o=jr){let i=0;for(let a of e){i+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:i,available:!0};if(!c.skipped)return m}catch(c){if(!ry(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:[ny]};let s=i===0;throw new l(s?"No actionable items matched the selection filters":"No actionable item remained available to claim",s?d.NOT_FOUND:d.CONFLICT,{code:ny,why:s?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[s?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function qr(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let i=await A(o),s=C(r.author,i.author_default),a=xn(s),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await ae({pmRoot:o,settings:i,id:e,op:"release",author:s,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){Lr(_,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await pc({pmRoot:o,principal:a,itemId:u.item.id});let p=F(i.schema),f=Da(u.item.status,p)===Da(p.in_progress_status,p);return{item:u.item,released_by:s,changed_fields:u.changedFields,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${u.item.id} remains ${u.item.status} and unclaimed. If work is paused, run pm release ${u.item.id} --pause to move it to ${p.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]="7f0e8f0f-bef3-5d61-b851-7582a03430b6")}catch{}})();async function ul(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 pl(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start requires an explicit item id and cannot be combined with --next or --if-available",d.USAGE);let r=await A(E(process.cwd(),n.path)),o=bs(F(r.schema)),i=await jr(e,t.force===!0,n,t),s=await ul(e,"claim",()=>it(e,Ut(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:e,action:"start_task",claim:i,update:s}}async function fl(e,t,n){let r=await A(E(process.cwd(),n.path)),o=F(r.schema).open_status,i=await it(e,Ut(t,{status:o},["assignee","pause"]),n),s=await ul(e,"update",()=>qr(e,t.force===!0,n,t));return{id:e,action:"pause_task",update:i,release:s}}async function _l(e,t,n,r){let o=await vt(e,t,n,r),i=await ul(e,"close",()=>qr(e,n.force===!0,r,n));return{id:e,action:"close_task",close:o,release:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="31407e14-880c-5637-a2d5-3569e575e729")}catch{}})();async function iy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(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 s=e.args.next===!0||r.next===!0?await oy(o,e.global,i,i):await jr(Kr(e,r),o,e.global,i);return Se(s,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Kr(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function hl(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function sy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return r.releaseAssignment===!0?_n(e,"close_task"):Se(await vt(Kr(e,r),hl(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function _n(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=_e(e.args,e.options),i=Kr(e,o),s=Ut(o,{force:e.force===!0||o.force===!0}),a=t==="start_task"?await pl(i,s,e.global):t==="pause_task"?await fl(i,s,e.global):await _l(i,hl(e,o),s,e.global);return Se(a,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function ay(e){if(e.options.pause===!0)return _n(e,"pause_task");let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=await qr(Kr(e,r),e.force===!0,e.global,r);return Se(o,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function cy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await ml(Kr(e,r),hl(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]="fc60339e-561c-5ac3-bdb3-116bd55e35b5")}catch{}})();function As(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 ${Du(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]="d9a4fa9f-2f70-5ce9-b9c0-24e58b120420")}catch{}})();var i0=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],ly=["brief","standard","deep"],uy="plan-step-",kl="draft",bl=["bug-investigation","feature-implementation","refactoring-sprint"],dy={"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 s0(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(dy,t)?dy[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${bl.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${bl[0]}`]});return n.map(r=>({...r}))}function a0(e,t){return t>0?Math.round(e/t*100):0}function py(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function ze(e){return Array.isArray(e)?e.flatMap(t=>Dn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Dn(e,{unique:!1}):[]}function xe(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function fy(e,t=kl){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ca.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${ca.join(", ")}`,d.USAGE);return r}function Sl(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=la.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${la.join(", ")}`,d.USAGE);return r}function _y(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ma.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${ma.join(", ")}`,d.USAGE);return r}function c0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=da.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${da.join(", ")}`,d.USAGE);return n}function l0(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=ly.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${ly.join(", ")}`,d.USAGE);return n}function d0(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 gl=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function m0(e,t){let n=e,r={},o=[];for(let i of t){let s=i.startsWith("plan.")?i.slice(5):i;if(s.length!==0){if(!gl.has(s)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...gl].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...gl].join(",")}`}});return r}function El(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 Al(e){let t=El(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 Tl(e){let t=El(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 Cl(e){let t=El(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 u0(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=a0(t.completed,t.total),t}function p0(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${uy}${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 Wn(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(s=>s.order===o);if(i)return i}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function my(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 f0(e,t){let n=t.filter(s=>s.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 s of e.slice().sort((a,c)=>a.order-c.order)){let a=my(s);if(a){o.push({from_step:s.id,...a});continue}r.push(s)}return{targets:r,skipped:o}}let i=new Set;for(let s of t){let a=Wn(e,s);if(i.has(a.id))continue;i.add(a.id);let c=my(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function _0(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 h0(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function g0(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function De(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((s,a)=>s.order-a.order),r=u0(n),o=h0(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??kl,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:g0(n),linked_items:(e.dependencies??[]).map(s=>({id:s.id,kind:s.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function Ue(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!Ya(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function hy(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 y0(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function gy(e,t){let n=x(e.settings,R()),r=await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let o=await se(r,{schema:e.settings.schema});return hy(o.document.metadata),{document:o.document,itemId:r.id}}function v0(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of ze(e.related))t.push(`id=${n},kind=related`);for(let n of ze(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of ze(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function w0(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 b0(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||ze(e.dependsOn).length>0||ze(e.link).length>0}function k0(e){let t=e.stepTitle?.trim()||void 0,n=py(e.step),r=e.template?.trim()?s0(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function S0(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 ${bl[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 E0(e,t){let n=Sl(e.stepStatus,"pending"),r=Il(e,"depends_on"),o=xe(e.file).map(Al),i=xe(e.test).map(Tl),s=xe(e.doc).map(Cl),a=S();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:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function A0(e){let t=k0(e),n=b0(e);if(S0(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[E0(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((o,i)=>({id:`${uy}${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 yy(e,t,n=[]){Ce(e,t),n.length>0&&Mp(t,n)}async function T0(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=fy(e.mode,kl),i=c0(e.harness),s=e.fromSearch?.trim(),a=w0(e),{steps:c,hasPerStepDetailOptions:m}=A0(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 u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:xe(e.file),test:xe(e.test),doc:xe(e.doc),field:xe(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:v0(e),message:e.message??(s?`plan create (search: ${s})`:"plan create")};yy(e,f);let _=await jt(f,t),h=await ae({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let v=["plan_mode"];g.metadata.plan_mode=o,i&&(g.metadata.plan_harness=i,v.push("plan_harness"));let b=e.scope?.trim();b&&(g.metadata.plan_scope=b,v.push("plan_scope"));let k=e.resumeContext?.trim();return k&&(g.metadata.plan_resume_context=k,v.push("plan_resume_context")),g.metadata.plan_steps=c,v.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],v.push("plan_validation")),p&&(g.metadata.assignee=p,v.push("assignee")),{changedFields:v}}}),y=De(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ue(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function C0(e,t,n){let r=l0(t.depth),o=d0(t.fields),{document:i,itemId:s}=await gy(n,e),a=De(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:m0(a,o),next_actions:Ue(s,a),warnings:[],generated_at:S()}}function I0(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 ae({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){hy(o.metadata);let i=F(e.ctx.settings.schema);if(re(o.metadata.status,i)||Ya(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 s=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(s,o);n=c.resultStep;let m=s.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=I0(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function R0(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Sl(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:s,resultStep:a,itemId:c}=await st({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;vy(u,void 0,o,i);let f=O0(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=De(s.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ue(c,m),warnings:[],generated_at:S()}}function vy(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 O0(e,t,n){let r=Il(t,"depends_on"),o=xe(t.file).map(Al),i=xe(t.test).map(Tl),s=xe(t.doc).map(Cl),a=S();return{id:p0(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:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Il(e,t){let n=ze(e.dependsOn).map(u=>({id:u,kind:t})),r=ze(e.related).map(u=>({id:u,kind:"related"})),o=ze(e.blocks).map(u=>({id:u,kind:"blocks"})),i=ze(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),s=ze(e.link),a=_y(e.linkKind,t),c=e.linkNote?.trim(),m=s.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...i,...m]}async function yl(e,t,n,r){let{document:o,resultStep:i,itemId:s}=await st({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Wn(c,r.stepRef),p=S(),f=r.finalStatus??Sl(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return vy(c,u.status==="in_progress"?u.id:void 0,f,_),x0(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=De(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:i,next_actions:Ue(s,a),warnings:[],generated_at:S()}}function x0(e,t,n,r){P0(e,t,n),N0(e,t),e.status=n,e.updated_at=r,L0(e,n,r)}function P0(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 N0(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=xe(t.file).map(Al),o=xe(t.test).map(Tl),i=xe(t.doc).map(Cl);r.length>0&&(e.files=vl(e.files,r)),o.length>0&&(e.tests=vl(e.tests,o)),i.length>0&&(e.docs=vl(e.docs,i))}function vl(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 L0(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function $0(e,t,n,r,o){let{document:i,itemId:s,resultStep:a}=await st({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(m){let u=Wn(m,r),p=m.filter(_=>_.id!==u.id),f=Math.max(1,Math.min(o,p.length+1));return p.splice(f-1,0,u),p.forEach((_,h)=>{_.order=h+1,_.updated_at=S()}),m.length=0,m.push(...p),{changedSteps:[u.id],resultStep:u}}}),c=De(i.metadata,"standard");return{action:"reorder-step",plan:c,step:a,next_actions:Ue(s,c),warnings:[],generated_at:S()}}async function F0(e,t,n,r){let{document:o,itemId:i,resultStep:s}=await st({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let m=Wn(c,r),u=c.filter(p=>p.id!==m.id);return u.forEach((p,f)=>{p.order=f+1}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=De(o.metadata,"standard");return{action:"remove-step",plan:a,step:s,next_actions:Ue(i,a),warnings:[],generated_at:S()}}async function M0(e,t,n,r){let o=Il(t,_y(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:s,itemId:a,resultStep:c}=await st({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Wn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of o){let v=h(g);y.has(v)||(_.push(g),y.add(v))}if(f.linked_items=_,f.updated_at=S(),i){let g=p.metadata.dependencies??[],v=k=>`${k.kind}:${k.id}`,b=new Set(g.map(v));for(let k of o){let T=k.kind==="depends_on"?"blocked_by":k.kind,O={id:k.id,kind:T,created_at:S(),author:C(t.author,n.settings.author_default)};b.has(v(O))||(g.push(O),b.add(v(O)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=De(s.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ue(a,m),warnings:[],generated_at:S()}}async function D0(e,t,n,r){let o=ze(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:i,itemId:s,resultStep:a}=await st({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Wn(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=De(i.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ue(s,c),warnings:[],generated_at:S()}}async function wl(e,t,n,r){let o=_0(r,t);if(!o){let m=`--${r}-text`,u=`--${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> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let i=C(t.author,n.settings.author_default),{document:s,itemId:a}=await st({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=S();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:i,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=De(s.metadata,"deep");return{action:r,plan:c,next_actions:Ue(a,c),warnings:[],generated_at:S()}}async function U0(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(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),s=De(o.metadata,"brief");return{action:"resume",plan:s,next_actions:Ue(i,s),warnings:[],generated_at:S()}}async function G0(e,t,n){let r=fy(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(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),s=De(o.metadata,"brief");return{action:"approve",plan:s,next_actions:Ue(i,s),warnings:[],generated_at:S()}}function wy(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function j0(e,t){let n=De(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ue(e.itemId,n),warnings:wy(t),generated_at:S()}}function q0(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 K0(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of xe(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let c=s.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let[m,...u]=c,p=`${m}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new l(`Invalid --field entry "${o}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}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:q0(e.parent,e.planItemId,o)};yy(e.options,i,["description",...Object.keys(n)]);let s=await jt(i,{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:o.id})}return t}function z0(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let i=e.find(a=>a.id===r.id);if(!i)continue;let s=i.linked_items??[];s.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=s,i.updated_at=S()}}async function B0(e,t,n){let r=ze(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",i=x(n.settings,R()),s=be(o,i);if(!s)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await gy(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=f0(u,r);if(p.length===0){if(f.length>0)return j0(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await K0({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:s,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await st({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(v){return z0(v,p,_),{changedSteps:p.map(b=>b.id)}}}),g=De(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ue(y,g),warnings:wy(f),generated_at:S()}}function H0(e){if(e.subcommand==="create")return e;let t=py(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:Ce(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 V0(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 W0={create:(e,t)=>T0(e.options,e.global,t),show:(e,t)=>C0(bt(e,"show"),e.options,t),"add-step":(e,t)=>R0(bt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=hn(e,"update-step");return yl(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=hn(e,"complete-step");return yl(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 yl(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=V0(e);return $0(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=hn(e,"remove-step");return F0(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=hn(e,"link");return M0(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=hn(e,"unlink");return D0(n.id,e.options,t,n.stepRef)},decision:(e,t)=>wl(bt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>wl(bt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>wl(bt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>U0(bt(e,"resume"),e.options,t),approve:(e,t)=>G0(bt(e,"approve"),e.options,t),materialize:(e,t)=>B0(bt(e,"materialize"),e.options,t)};function Y0(e){let t=W0[e];if(!t)throw Te({command_path:"plan",token:e,allowed:i0});return t}async function by(e){let t=await y0(e.global),n=H0(e),r=await Y0(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:As(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]="3ef785ae-bb1e-59dd-993c-3be56ddc26c2")}catch{}})();var Sy=1,Ol="update-many",J0=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),X0=["--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(", "),Q0={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"},Z0=[{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"}],eO={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"},Ey=e=>{let t={};for(let[n,r]of Object.entries(e))J0.has(n)||r!==void 0&&(t[n]=r);return t},tO=e=>Object.keys(Ey(e)).length>0,Ay=e=>typeof e=="string"?e.trim():e,nO=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Rl=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},rO=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Ay(e)},oO={priority:nO,estimatedMinutes:Rl,order:Rl,rank:Rl,regression:rO},iO=(e,t)=>{if(t!==void 0)return(oO[e]??Ay)(t)},sO=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return eO[t]??t},Ts=(e,t)=>qe(e,t),aO=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],cO=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,lO=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",ky=(e,t)=>t===void 0?void 0:e[t],Yn=e=>Array.isArray(e)?e.length:0,dO=(e,t,n)=>{let r=n[e.addKey],o=ky(n,e.removeKey),i=Yn(r),s=Yn(o),a=n[e.clearKey]===!0,c=ky(n,e.replaceKey)===!0;if(![a,c,i>0,s>0].includes(!0))return;let m=aO(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:lO({replace:c,clear:a,removeCount:s}),clear:a,replace:c,add_count:i,remove_count:s,before_count:cO(e.field,m)}}},mO=(e,t)=>{let n=[];for(let r of Z0){let o=dO(r,e,t);o!==void 0&&n.push(o)}return n},uO=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],pO=(e,t)=>{if(![t.tags!==void 0,Yn(t.addTags)>0,Yn(t.removeTags)>0].includes(!0))return;let n=uO(e.tags),r=t.tags===void 0?n:Nt(t.tags),o=Nn(r,t.addTags),i=li(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),s=n.slice().sort((a,c)=>a.localeCompare(c));if(!Ts(s,i))return{field:"tags",before:n,after:i}},fO=(e,t)=>{let n=e.acceptance_criteria,r=ci(Pn(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(!Ts(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},_O=(e,t,n)=>{for(let[r,o]of Object.entries(Q0)){let i=n[r];if(i===void 0)continue;let s=t[o],a=iO(r,i);Ts(s,a)||e.push({field:o,before:s,after:a})}},hO=(e,t,n,r)=>{let o=ti(n,r,["update_many"]);for(let[i,s]of Object.entries(o)){let a=t[i];Ts(a,s)||e.push({field:i,before:a,after:s})}},gO=(e,t,n)=>{for(let r of n??[]){let o=sO(r),i=t[o];i!==void 0&&e.push({field:o,before:i,after:null})}},yO=(e,t,n={})=>{let r=e,o=[],i=pO(r,n);if(i&&o.push(i),_O(o,r,n),Yn(n.addAc)>0||Yn(n.removeAc)>0){let s=fO(r,n);s!==void 0&&o.push(s)}return o.push(...mO(r,n)),hO(o,r,n,t),gO(o,r,n.unset),{id:e.id,changes:o}},vO=(e,t)=>qp(e,t,{strict:!0,flagLabel:"--filter-status"}),wO=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)},bO=[({update:e})=>{e.priority!==void 0&&$n(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,R());if(!be(e.type,r))throw new l(Ot(e.type,r.types,xt(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&&Ln(e.estimatedMinutes,"estimated-minutes")}],kO=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of bO)i(o)},SO=async e=>{let t=await ii(e.pmRoot,Ol,e.rollbackId,Sy),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await si(t.items,(o,i)=>sn(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}},EO=async e=>{let t={schema_version:Sy,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 oi(e.pmRoot,Ol,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},AO=(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))},xl=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},TO=async e=>{let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:F(n.schema),runtimeFieldRegistry:et(n.schema)}},CO=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Ir(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return SO({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},IO=async e=>{vO(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=yO(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:AO(e.options.list?.ids,r)}},RO=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:[],...xl(e)}),OO=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:[],...xl(e)}),xO=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 s=Ha({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await it(i.id,s,e.global);t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(s){t.push({id:i.id,status:"failed",error:En(s)})}}return{rows:t,updatedIds:n}},PO=async e=>{if(e.plan.actionable.length===0)return OO(e.plan);let t=S(),n=ri(Ol,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),i=e.options.checkpoint===!1?void 0:await EO({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}),s=await xO({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>s.rows.filter(f=>f.status===p).length,c=a("updated"),m=a("skipped"),u=a("failed");return{...en({applied:c,skipped:m,failed:u,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:u,rows:s.rows,ids:s.updatedIds,...xl(e.plan)}},Ty=async(e,t)=>{let n=await TO(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Ha(await ll(e.update))});let o=Ey(e.update);if(wO(e.list),r!==void 0)return CO({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!tO(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${X0}), or pass --dry-run for a filter-only preview.`,d.USAGE);kO(e.update,n.settings,n.statusRegistry,n.pmRoot),dl(e.update);let i=await un({pmRoot:n.pmRoot,dependencies:Es(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),s=await IO({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:i});return await un({pmRoot:n.pmRoot,dependencies:Es(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:s.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?RO(s):PO({runtime:n,options:e,global:t,plan:s})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4e85b9bc-3387-5fb8-ac8b-c8f115c82b60")}catch{}})();function NO(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 LO(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 $O(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 Cy(e,t,n){let r=NO(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),s=[t.since,t.eventType].some(h=>h!==void 0),a=$O(t.since),c=yr(t.limit),m=await Bn(e,{...t,...s?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,s].includes(!0)},n,{input:await Bi(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>zn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:LO(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."]}}),u=t.eventType?.trim(),p=m.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),v=[!u,h.event_type===u].includes(!0);return[!s,[y,g,v].every(Boolean)].includes(!0)}),f=s?Ic(p,c):p,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...s?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}import WO from"node:path";import FO from"node:fs/promises";import Iy 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]="ff76c0f3-d8cf-51de-a7e6-acb0a4942268")}catch{}})();var MO="templates",DO=".json",UO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,GO=Xo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),jO=new Set(GO);function qO(e){let t=e.trim();if(!UO.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 Ry(e){return Iy.join(e,MO)}function Oy(e,t){return Iy.join(Ry(e),`${t}${DO}`)}async function KO(e){await I(e)}function xy(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function zO(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(jO.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 xy(t)}function BO(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 s=o.trim();if(s.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof i=="string"){r[s]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[s]=[...i];continue}throw new l(`Template "${t}" contains invalid value for option "${s}".`,d.GENERIC_FAILURE)}return xy(r)}function HO(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=BO(r.options,t),i=S();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 VO(e,t){let n=await Z(Oy(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return HO(n,t)}async function Pl(e,t,n){let r=E(process.cwd(),n.path);await KO(r);let o=qO(e),i=zO(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let s=S(),a=Oy(r,o),c=s;await G(a)&&(c=(await VO(r,o)).created_at);let m={name:o,created_at:c,updated_at:s,options:i},u=await A(r);return await FO.mkdir(Ry(r),{recursive:!0}),await rt({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
22
+ `,op:"templates:save",author:C(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,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]="5529deea-21db-509b-9562-d5e08dfc004a")}catch{}})();var $y=["list","show","apply","lint"],YO="schema-types",JO="schema-statuses",XO="schema-fields";function Cs(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Fy(){let{profiles:e,warnings:t}=_u(Cs());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:wu(n.definition)})),warnings:t,generated_at:S()}}function My(e){let t;try{t=jo(e,Cs())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...bu(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Dy(e){let t;try{t=jo(e,Cs())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=Ju(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:S()}}function QO(e,t){return WO.join(e,"templates",`${t}.json`)}async function ZO(e,t){let n=await Z(QO(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 Py(e,t,n,r){let o=new Map;for(let i of r.templates){let s=await ZO(e,i.name);s!==void 0&&o.set(i.name,s)}return{typesRaw:await Z(ut(e,t.files.types,mt.types)),statusesRaw:await Z(ut(e,t.files.statuses,mt.statuses)),fieldsRaw:await Z(ut(e,t.files.fields,mt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Jn(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 Ny(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Jn(t.types.changes),statuses:Jn(t.statuses.changes),fields:Jn(t.fields.changes),workflows:Jn(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Jn(t.config.changes),templates:Jn(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,s)=>i.localeCompare(s)),generated_at:S()}}async function ex(e){await I(e)}function tx(e){try{let t=jo(e,Cs());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Uy(e,t,n){let r=E(process.cwd(),n.path);await ex(r);let o=tx(e),i=o.profile,s=o.warnings,a=t.dryRun===!0,c=await A(r),m=qo(c.schema);if(a){let v=await Py(r,m,c,i),b=Ly(i,v);return Ny(i,b,!1,!0,[...s])}let u=C(t.author,c.author_default),p=Np(c),f=!!t.force,_=[...s],h=[],y=async v=>{h.push(await Ae(r,v,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(YO),await y(JO),await y(XO);let v=await Py(r,m,c,i);if(g=Ly(i,v),g.types.changed){let b=ut(r,m.files.types,mt.types);await rt({pmRoot:r,filePath:b,raw:Go(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(i.types.map(O=>lu(O).name)),T=g.types.file.definitions.filter(O=>k.has(O.name));await wf(r,T,_,"profile:apply-type-folder"),_.push(...await Y({path:b,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let b=ut(r,m.files.statuses,mt.statuses);await rt({pmRoot:r,filePath:b,raw:vu(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let b=ut(r,m.files.fields,mt.fields);await rt({pmRoot:r,filePath:b,raw:hu(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await Y({path:b,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let b of g.config.changes){if(b.status==="unchanged")continue;let k=zo(b.key);k!==void 0&&Bo(c,k,b.value)}c.schema.type_workflows=g.workflows.result,await $e(r,c,"profile:apply-config")}for(let b of g.templates.changes)b.status!=="unchanged"&&await Pl(b.name,{...b.options},n)}finally{for(let v of h.reverse())try{await v()}catch{}}return Ny(i,g,g.changed,!1,_)}function Ly(e,t){try{return Xu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import cx from"node:fs/promises";import $l 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]="451970e8-8403-5527-b795-a873241c015e")}catch{}})();var jy=10,gn="https://schema.unbrained.dev/pm/eval-query-set/v1";var Is={schema:gn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Ye=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},nx=new Set(["keyword","semantic","hybrid"]);function Gy(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 rx(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=Gy(r,n),i=Array.from({length:t.size},()=>1),s=Gy(i,n);return s===0?0:o/s}function ox(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 Nl(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 ix(e,t,n){return n<=0?0:Nl(e,t,n)/n}function sx(e,t,n){return t.size===0?0:Nl(e,t,n)/t.size}function qy(e,t,n){return{ndcg:rx(e,t,n),mrr:ox(e,t,n),precision:ix(e,t,n),recall:sx(e,t,n),relevant_total:t.size,retrieved_relevant:Nl(e,t,n)}}function Ky(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 ax(e,t){if(typeof e!="object"||e===null)throw new Ye(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Ye(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Ye(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new Ye(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new Ye(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!nx.has(n.mode)))throw new Ye(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:N_(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Ll(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==gn)throw new Ye(`Unsupported eval query set schema; expected "${gn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Ye('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Ye("Eval query set must contain at least one query");return{schema:gn,queries:n.map((r,o)=>ax(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]="d4020969-4ce5-5f87-ae41-f5a3dec0a197")}catch{}})();var lx=$l.join("search","eval-queries.json"),Fl={schema:gn,examples:[JSON.stringify(Is)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},dx=new Set(["keyword","semantic","hybrid"]),mx=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!dx.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},ux=e=>{if(e===void 0||e==="")return jy;let t=Vd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},px=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},qt=e=>Math.round(e*1e4)/1e4,fx=async e=>{try{return await cx.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Fl,examples:[`echo '${JSON.stringify(Is)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},_x=(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,Fl)}},hx=e=>{try{return Ll(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Fl)}},gx=async e=>hx(_x(await fx(e),e)),yx=async(e,t,n,r)=>{let o=e.mode??t,s=(await Or(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=qy(s,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:L_(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:qt(a.ndcg),mrr:qt(a.mrr),precision:qt(a.precision),recall:qt(a.recall)}}},vx=(e,t,n,r)=>{let o=Ky(n);return{k:e,query_count:t.length,aggregate:{ndcg:qt(o.ndcg),mrr:qt(o.mrr),precision:qt(o.precision),recall:qt(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)}},zy=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=ux(e.k),o=mx(e.mode),i=px(e.failUnder),s=e.queries?$l.resolve(process.cwd(),e.queries):$l.join(n,lx),a=await gx(s),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await yx(u,o,r,t);m.push(f),c.push(p)}return vx(r,c,m,i)};import{readFile as wx,writeFile as bx}from"node:fs/promises";import kx 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]="47487ad3-22a0-52ac-8a42-ebaca439cb6e")}catch{}})();var By=["item","history","relationship","json"];function Sx(e){let t=e.trim().toLowerCase();if(By.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${By.join(", ")}.`,d.USAGE)}function Ex(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 Ml(e,t){try{return await wx(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function Ax(e){let t=E(process.cwd(),e.path);return await G(ne(t))?A(t):null}function Tx(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Hy(e,t){let n=Sx(e.artifact),r=Ex(e.prefer),o=kx.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Ml(e.basePath,"base"),Ml(e.oursPath,"ours"),Ml(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=Xf(i,s,a);c=_.merged,p.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 _=Qf(i,s,a);c=_.merged,p.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 Ax(t),h=Tx(e.itemPath??o,_),y=Tt(R()),g=Zf(i,s,a,{format:h,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=g.merged,u.push(...g.conflict_fields),p.item={fields_from_theirs:g.fields_from_theirs,union_fields:g.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let v=vp(c,{format:h,schema:_?.schema,extensionFieldNames:y}),b=v.metadata,k=[...new Set([...g.fields_from_theirs,...g.union_fields,...g.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:g.fields_from_theirs,unionFields:g.union_fields,mergedFieldHashes:Object.fromEntries(k.map(T=>[T,Jf(T==="body"?v.body:b[T])])),decisions:g.conflict_decisions,operation:await t_(process.cwd(),e.itemPath)}}}else{let _=e_(i,s,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await bx(o,c,"utf8"),m!==void 0){let _=await r_(m);_!==null&&(p.receipt=nn(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.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"&&p.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:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5fd3624a-d36b-58e6-8053-f2c0626e0c10")}catch{}})();async function Vy(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await n_(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Gt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Gt(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 Oi(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as Cx}from"node:fs/promises";import Ix 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]="017ec565-4b8d-5da3-badc-e9f4ca3ec433")}catch{}})();var Rx=4;function Wy(e){let t=e.checks.find(a=>a.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,s=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:s}}async function Ox(e,t){let n=[];for(let r of t){let o;try{o=await Cx(Ix.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 s;try{s=JSON.parse(i)}catch{continue}let a=c_(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!a_(a)||a.eventTimestamp===void 0||Yo(a.eventTimestamp,s_)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function xx(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 Gt(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 Px(e){try{return{status:"fulfilled",value:await Gt(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 Nx(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 Lx(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=>Oi(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}async function Yy(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Wy(o),s=await Ox(r,i.coordinates),a=await Si(r),c=a??r,m=await o_(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 u=await xx({candidates:s,options:e,global:t}),p=m.receipts,f=await Vy({cwd:a,receipts:p,dryRun:n,author:e.author,message:e.message,global:t}),_=new Set(f),h=new Map;for(let j of p.filter(le=>!_.has(le.id))){let le=h.get(j.item_id)??[];le.push(j),h.set(j.item_id,le)}let y=Object.fromEntries([...h].map(([j,le])=>[j,{merge:{receipts:le.map(nn)}}])),g=Object.fromEntries([...h].map(([j,le])=>[j,{gitWorkspaceRoot:a,receipts:le}])),v=await Pi({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:y,...p.length>0?{mergeReceiptProofById:g}:{}},t),b=new Set(v.streams.map(j=>j.id)),k=[...h.keys()].filter(j=>!b.has(j)),T=await Pf(k,Rx,j=>Px({id:j,dryRun:n,options:e,global:t,auditContext:y[j],mergeReceiptProof:g[j]}));Nx({receiptOnlyIds:k,results:T,repair:v});let O=await Lx({dryRun:n,pendingReceipts:p,repair:v,receiptWorkspaceRoot:c}),L=await $i({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),$=u===0?o:await Tr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),K=Wy($),J=L.checks.every(j=>j.status==="ok"),z=n?p.length===0:O+f.length===p.length,ue=[v.totals.failed===0,J,z,K.count===0,!K.truncated].every(Boolean),oe=i.truncated||K.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,Be=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",oe,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:ue?["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.",oe,...s.length>0&&u===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(j=>j!==void 0);return{ok:ue,dry_run:n,repair:v,receipts:{pending_before:p.length,reconciled:O,abandoned:f.length,summaries:p.map(nn),missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:u,missing_history_references_after:K.count},validation:L,guidance:Be,generated_at:L.generated_at}}import{createHash as $x}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]="117a463a-c0ab-569f-92e9-e85d14a1cf91")}catch{}})();var Qy=1,Zy=/^[A-Za-z0-9_-]+$/,Fx=100,Jy=1e3;var gB=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Je(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function Mx(e){return $x("sha256").update(Yt({type:Je(e.type),author:Je(e.author),item:Je(e.item),harness:Je(e.harness),agent_instance:Je(e.agentInstance),provenance:Je(e.provenanceFilter)})).digest("hex").slice(0,24)}function Xy(e,t){let n={version:Qy,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 Dx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Qy,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 Ux(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Zy.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(!Dx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function Gx(e){let t=e??Fx;if(!Number.isSafeInteger(t)||t<0||t>Jy)throw new l(`Mutation event limit must be an integer from 0 to ${Jy}.`,d.USAGE,{code:"invalid_event_limit"});return t}function jx(e,t){let n=e?.trim();if(!n)return{};if(Zy.test(n))return{cursor:Ux(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 qx(e,t){let n=await Ga(e,t);if(n===null){if(!await kp(e))return{...await Sp(e,t),source:"authoritative_history"};n=await Ga(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 Kx(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 Rs(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=Gx(e.limit),r=Kx(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,s=T_(o.agent_identity.harness_signals),a=C_({provenance:e.provenanceFilter},s),c=Je(e.harness),m=Mx(e),{cursor:u,sinceTimestamp:p}=jx(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:Je(e.type),authors:Je(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:Je(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:Je(e.item),limit:n},_=await qx(t,f),h=_.events.map(y=>({...r==="row"?{cursor:Xy(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:I_(y.entry,i,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:Xy(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:R_(_.events.map(y=>y.entry),i,s)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a196ae-61e1-528d-99a2-83eb9e11158b")}catch{}})();var zx="1h",Bx="now",Hx="+1d";function Kt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function ev(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 Ce(n,r)}async function tv(e,t,n,r){let o=ev(e,t,n),i=[];return Kt(i,"start",n.start??Bx),n.end!==void 0?Kt(i,"end",n.end):Kt(i,"duration",n.duration??zx),Kt(i,"location",n.location),Kt(i,"timezone",n.timezone),n.allDay===!0&&Kt(i,"all_day","true"),o.event=[i.join(",")],jt(o,r)}function nv(e,t,n){return tv("Meeting",e,t,n)}function rv(e,t,n){return tv("Event",e,t,n)}function ov(e,t,n){let r=ev("Reminder",e,t),o=[];return Kt(o,"at",t.at??Hx),Kt(o,"text",t.text??e),r.reminder=[o.join(",")],jt(r,n)}import Br from"node:crypto";import{cp as iv,lstat as Vx,mkdir as yn,readFile as Xn,readdir as Ul,rename as cv,rm as jl,writeFile as Os}from"node:fs/promises";import M 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]="91604cb2-8afd-585e-9c18-26e223df25bc")}catch{}})();var lv="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var dv=M.join("runtime","workspace-snapshots"),Wx=new Set(["checkpoints","locks","runtime","search","transactions"]),Yx=/^[a-z0-9][a-z0-9._-]*$/,zr="sdk-workspace-transaction",Dl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},mv={renameEntry:cv,removeEntry:async e=>{await jl(e,{recursive:!0,force:!0})}},Gl=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 Xn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==zr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await te(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
23
+ `)}};async function uv(e,t=""){let n=await Ul(M.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,s)=>i.name.localeCompare(s.name))){if(t.length===0&&Wx.has(o.name))continue;let i=M.posix.join(t.replaceAll(M.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await uv(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function pv(e){let t=await uv(e),n=Br.createHash("sha256"),r=[],o=0;for(let s of t){let a=await Xn(M.join(e,s));r.push(a),o+=a.byteLength,n.update(s),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let i=n.digest("hex");return{manifest:{schema:lv,fingerprint:i,files:t,bytes:o},contents:r}}function sv(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
24
+ `).filter(t=>t.trim().length>0).length}async function Jx(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 s=>[s,await Xn(M.join(e,s))]));for(let[s,a]of i)n.set(s,a)}return n}function ql(e){if(!Yx.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 fv(e,t){return ir(`workspace_snapshot_${e}`,t,{codes:{capacity:Dl.capacity.code,permission:Dl.permission.code,resource:Dl.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 vn(e){return M.join(e,dv)}function _v(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 hv(e,t){try{return JSON.parse(await Xn(e,"utf8"))}catch(n){throw Ct(n)?_v(t):n}}async function av(e,t,n){try{await jl(e,{recursive:n})}catch(r){throw Ct(r)?_v(t):r}}async function Xx(e,t,n=mv){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 Qx(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 Zx(e,t){return ql(t),/^[a-f0-9]{64}$/.test(t)?t:(await hv(M.join(vn(e),"refs",`${t}.json`),t)).fingerprint}async function Kl(e,t={}){if(t.name!==void 0&&(ql(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 pv(e),o=vn(e),i=M.join(o,"objects",n.fingerprint),s=!1;try{s=(await Vx(i)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&Ct(a)))throw a}if(!s){let a=M.join(o,"objects",`.create-${process.pid}-${Br.randomUUID()}`);await fv("create_object",async()=>{await yn(M.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=M.join(a,"files",m);await yn(M.dirname(u),{recursive:!0}),await Os(u,r[c])}await Os(M.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
25
+ `,"utf8"),await yn(M.dirname(i),{recursive:!0})}),s=await Xx(a,i)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=M.join(o,"refs");await yn(c,{recursive:!0});let m=M.join(c,`.ref-${process.pid}-${Br.randomUUID()}`);await Os(m,`${JSON.stringify(a,null,2)}
26
+ `,"utf8"),await cv(m,M.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:s}}async function Hr(e,t){let n=await Zx(e,t),r=await hv(M.join(vn(e),"objects",n,"manifest.json"),t);if(r.schema!==lv||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function zl(e){let t=vn(e),n=await Ul(M.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&Ct(o))return[];throw o}),r=await Ul(M.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&Ct(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Hr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Xn(M.join(t,"refs",o),"utf8"))))}}async function Bl(e,t){let n=await Hr(e,t),{manifest:r,contents:o}=await pv(e),i=new Map(r.files.map((p,f)=>[p,o[f]])),s=await Jx(M.join(vn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=i.get(p),_=s.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=sv(i.get(p)),_=sv(s.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function gv(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,s=await Ae(e,zr,o,r,!1,!1,i),a=new Gl(mo(e,zr),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Bl(e,t),f=await Hr(e,t),_=await Kl(e),h=f.fingerprint,y=vn(e),g=M.join(y,"objects",h,"files"),v=M.dirname(e),b=M.basename(e);c=M.join(v,`.${b}.restore-${Br.randomUUID()}`);let k=M.join(v,`.${b}.backup-${Br.randomUUID()}`);await fv("restore_stage",async()=>{await yn(c,{recursive:!0}),await iv(g,c,{recursive:!0,force:!1}),await yn(M.join(c,"runtime"),{recursive:!0}),await iv(y,M.join(c,dv),{recursive:!0,force:!1})});let T=await xp({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),O=M.relative(c,T.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let L=mo(c,zr);return await yn(M.dirname(L),{recursive:!0}),await Os(L,await Xn(mo(e,zr)),{flag:"wx"}),m=!0,await Qx(c,e,k,mv,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:O,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([jl(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await s()}}}async function yv(e,t){ql(t);let n=vn(e);if(!/^[a-f0-9]{64}$/.test(t))return await av(M.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await zl(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await av(M.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66cead7f-c3f3-5073-82a5-ad1535f3f611")}catch{}})();function Vr(e){let t={...e.args,...e.options};return Ce(e.options,t)}function kt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Qn(e){return typeof e=="string"?[e]:ge(e)}function vv(e){return zy(Vr(e),e.global)}function wv(e){let t=Vr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Rs({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Qn(t.type),author:Qn(t.author),item:Qn(t.item),limit:t.limit===void 0?void 0:Fe(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Qn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Qn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Qn(t.provenanceFilter)}})}function bv(e){let t=Vr(e),n=kt(t,"subcommand");if(n==="install")return pf({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Yy({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return i_({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return Hy({artifact:kt(t,"artifact"),basePath:kt(t,"basePath"),oursPath:kt(t,"oursPath"),theirsPath:kt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Te({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function kv(e){let t=Vr(e),n=kt(t,"subcommand");if(n==="position")return $_(e.global);if(n!=="snapshot")throw Te({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??kt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return Kl(o,{name:w(t,"name")});if(r==="list")return zl(o);let i=kt(t,"target");if(r==="inspect")return Hr(o,i);if(r==="delete")return yv(o,i);if(r==="restore")return t.dryRun===!0?Bl(o,i):gv(o,i,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Fe(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Fe(t.lockWaitMs,"lockWaitMs")});throw Te({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function xs(e){let t=Vr(e),n=kt(t,"title");return e.action==="meet"?nv(n,t,e.global):e.action==="event"?rv(n,t,e.global):ov(n,t,e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="086d2640-2a64-554a-9e40-a8f6994ae3a8")}catch{}})();function Sv(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ge(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import FP from"node:fs/promises";import jv 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]="60090339-2f94-5f22-be47-518498838b92")}catch{}})();function Ps(e,t,n,r,o,i="min"){let s=o==="min"?e-t:t-e,a=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return s<0||s===0&&r!==null&&a<0}function eP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(Ps(f,s,p,o,"min")&&(s=f,o=p),Ps(f,a,p,i,"max","max")&&(a=f,i=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function Ev(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>eP(_,h)),i=0,s=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(i+=_.lines,s+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);Ps(h,m,_.id,a?.id??null,"min")&&(m=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);Ps(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:s,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as nP}from"node:crypto";import{execFile as rP}from"node:child_process";import Cv from"node:path";import{promisify as oP}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39d2b5aa-c6f3-57ac-adb4-e775bc838828")}catch{}})();var Av=1;function tP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Hl(e){if(e===null)return{format_version:Av,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Av||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!tP(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c800f76b-2867-51f5-80d6-fb7b1c61f9e4")}catch{}})();var iP=oP(rP),sP=50,Tv=1e3,aP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Iv(e){let t=e.trim().toLowerCase();if(!aP.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function cP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Wr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function lP(e){let t=e??sP;if(!Number.isSafeInteger(t)||t<0||t>Tv)throw new l(`Improvement observation limit must be an integer from 0 to ${Tv}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Rv(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function dP(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Iv(n.metric),o=cP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let i=await uP(e,n.revision),s=Wr(n.source,"source"),a=Wr(n.itemId,"itemId"),c=Wr(n.unit,"unit"),m=Wr(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,s??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Rv(n.observedAt??S(),"observedAt"),...i,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...s===void 0?{}:{source:s},...m===void 0?{}:{idempotency_key:m}};return{id:nP("sha256").update(Yt(u)).digest("hex").slice(0,24),...u}}function mP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function uP(e,t){let n=Wr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await iP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Yd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function pP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Ov(e,t={}){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await dP(n,r,e),i=Cv.join(n,"improvement-ledger.json"),s=await ni({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Hl(a),m=mP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${Yt(c)}
27
+ `,result:o})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function xv(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=e.metric===void 0?void 0:Iv(e.metric),r=e.since===void 0?void 0:Rv(e.since,"since"),o=lP(e.limit),s=Hl(await Z(Cv.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of s){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...s].reverse().slice(0,o),total:s.length,truncated:s.length>o,trends:[...a].map(([,c])=>pP(c)).sort((c,m)=>c.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e7a7f40-523d-590f-8aea-90b65535506e")}catch{}})();function Pv(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function fP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function _P(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Vl(e=pr,t=On){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function hP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Wl(e,t=On,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let s=`${o.agent_harness}\0${i}`,a=r.get(s)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(s,a)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function gP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),s=i.filter(c=>c.entries>=r),a=s.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:s.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:a}}function yP(e){let t=[...e].sort((i,s)=>i.ts.localeCompare(s.ts)||i.author.localeCompare(s.author)||i.op.localeCompare(s.op)||i.before_hash.localeCompare(s.before_hash)||i.after_hash.localeCompare(s.after_hash)),n=new Map,r=new Map;for(let i of t){let s=i.agent_episode,a=Pv(i),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(i);continue}let u={id:a.id,...s?.label===void 0?{}:{label:s.label},...s?.parent_id===void 0?{}:{parent_id:s.parent_id},source:a.source,entries:[i],children:[]};n.set(c,u),s!==void 0&&r.set(a.id,u)}let o=[];for(let i of n.values()){let s=i.parent_id?r.get(i.parent_id):void 0;s&&fP(i,s,r)?s.children.push(i):o.push(i)}return _P(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0eeefcd-2202-55c6-94e9-0372fcfe0c87")}catch{}})();var vP=1e4,Nv=1e5,wP=1e3,bP=30,kP=["append","comment","docs","file","learning","note","test_run"];function SP(e){let t=e??vP;if(!Number.isSafeInteger(t)||t<1||t>Nv)throw new l(`History analytics event limit must be an integer from 1 to ${Nv}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function Lv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function EP(e){let t=e?.trim();if(!t)return new Date(Date.now()-bP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function $v(e,t){let n=SP(t.eventLimit),r=EP(t.since),o=[],i=r,s=!1;for(;o.length<n;){let a=await Rs({pmRoot:e,since:i,limit:Math.min(wP,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),s=a.has_more,i=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:s,...s?{next_cursor:i}:{},source:"history_event_index"}}}function AP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function TP(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function CP(e){return kP.some(t=>e.startsWith(t))}function Fv(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function IP(e,t,n){let r=new Map,o=new Map,i=new Map;for(let s of t){let a=AP(s.entry,e),c=TP(s.entry),m=o.get(s.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(s.item_id,u),!a)continue;let p=Fv(r,a);p.events+=1,CP(s.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,i.set(s.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:i}}function RP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let s=t.get(i);s&&(Fv(e,s).defectEscapes+=1)}}}function OP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function xP(e,t,n,r,o,i){let{buckets:s,lastCloseValue:a}=IP(e,t,r);return RP(s,a,n),{dimension:e,status:s.size===0?"unavailable":"available",rows:[...s].map(([c,m])=>OP(c,m,o,i)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function PP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function NP(e,t,n){let r=Vl(t),o=Wl(e,On,n),i=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),s=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:i,undeclared:s,warnings:[...i.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...s.map(a=>`provenance_dimension_undeclared:${a}`)]}}function Mv(e,t=pr,n={}){let r=Lv(n.minimumSample);return{...NP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function Dv(e,t,n,r={}){let o=Lv(r.minimumSample),i=PP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(s=>xP(s,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c81415a5-81fa-57ed-936f-236841e5f066")}catch{}})();var LP=32;function $P(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Yr(e,t){let n=$P(e).map(o=>{let[i,...s]=o.split(","),a=i.indexOf("="),c=i.slice(0,a).trim(),m=i.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of s){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,i)=>o.name.localeCompare(i.name)).slice(0,LP)}function Uv(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Gv(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,s)=>s.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a567e72a-faff-580d-b9ae-e2ebfa492b89")}catch{}})();function MP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function DP(e,t,n,r,o){let i=wr(e,"type",r),s=new Set(i.rows.map(f=>f.key)),a=t.filter(f=>!s.has(f)),m=(o?[...i.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=MP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function UP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function GP(e){let t=jv.join(e,"history");if(!await G(t))return[];await In({path:t,scope:"project"});let n=(await FP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=jv.join(t,o),s=await Z(i);s!==null&&(await In({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:s}))}return r}async function jP(e,t){let n=[],r=S();for(let o of Yr(t.observe,r))n.push(await Ov({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function qP(e,t,n){let r={};return t.byAssignee&&(r.assignee=wr(e,"assignee",n)),t.byTag&&(r.tag=wr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=wr(e,"priority",n)),r}async function KP(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},s=o.provenanceCoverage||o.fleetAttribution?await $v(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&s?Mv(s,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&s?Dv(s,t,r,i):void 0}}function zP(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:S()}}async function Yl(e,t={}){let n=E(process.cwd(),e.path);await I(n);let r=await A(n),o=await jP(e,t),i=x(r,R()),s=F(r.schema),a=t.fieldUtilization?await Wp(n,r.item_format,i.type_to_folder,void 0,r.schema):await fe(n,r.item_format,i.type_to_folder,void 0,r.schema);await Gp({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=wi(s),m=DP(a,i.types,s.definitions.map(k=>k.id),c,t.includeEmpty===!0),u=await GP(n),p=0;for(let k of u)p+=UP(k.raw);let f=t.storage?Ev(u):void 0,_=t.metadataCoverage?nf(a,c):void 0,h=qP(a,t,c),y=t.fieldUtilization?rf(a):void 0,g=t.measurements===!0||o.length>0?await xv({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:b}=await KP(n,a,r,s.terminal_statuses,t);return zP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:o,provenanceCoverage:v,fleetAttribution:b})}import BP from"node:fs/promises";import zt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bc2412e-9aa0-55ea-bc51-97a6bb9b4763")}catch{}})();var Vv=zt.join("runtime","telemetry","events.jsonl"),Wv=zt.join("runtime","telemetry","state.json"),HP=zt.join("runtime","telemetry"),VP=20,Yv=Jt.filter(e=>e.lifecycle==="deprecated"),qv=["status","flush","stats","clear"],Kv=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Jl=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,zv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},WP=e=>({command:Jl(e.event.command,"<unknown>"),eventType:Jl(e.event.event_type,"unknown"),eventSchemaVersion:zv(e.event.schema_version),clientSchemaVersion:zv(e.client_schema_version)}),YP=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),JP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},XP=e=>{let t=e?.command_resolution;return Jl(t,"")||void 0},Jv=(e,t)=>{e[t]=(e[t]??0)+1},QP=(e,t)=>{let n=JP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=XP(t);r!==void 0&&Jv(e.resolution_counts,r)},ZP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Bv=(e,t)=>{t!==void 0&&e.add(t)},eN=(e,t)=>{let n=WP(t),r=e.get(n.command)??YP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,ZP(t.attempts)),Jv(r.event_type_counts,n.eventType),Bv(r.event_schema_versions,n.eventSchemaVersion),Bv(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&QP(r,t.event.payload),e.set(n.command,r)},tN=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,s)=>i-s),o=Object.entries(t.resolution_counts).sort((i,s)=>i[0].localeCompare(s[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,s)=>i[0].localeCompare(s[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,s)=>i-s),client_schema_versions:[...t.client_schema_versions].sort((i,s)=>i-s),...r.length>0?{duration_p50_ms:Kv(r,.5),duration_p95_ms:Kv(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},nN=e=>{let t=(e??"status").trim().toLowerCase();if(qv.includes(t))return t;throw Te({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:qv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Ql=()=>{throw new l("--limit must be a positive integer",d.USAGE)},Xv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Ql():e,rN=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Ql():Xv(Number.parseInt(t,10))},oN=e=>e===void 0?VP:typeof e=="number"?Xv(e):typeof e=="string"?rN(e):Ql(),iN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},sN=e=>{try{let t=JSON.parse(e);return iN(t)?t:void 0}catch{return}},aN=e=>e===null?[]:e.split(`
28
+ `).map(t=>t.trim()).filter(t=>t.length>0),Qv=e=>{let t=aN(e),n=[],r=0;for(let o of t){let i=sN(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},cN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lN=e=>{try{let t=JSON.parse(e);return cN(t)?t:{}}catch{return{}}},Xl=async e=>{let t=await Z(e);return t===null||t.trim().length===0?{}:lN(t)};function dN(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function mN(e,t,n){let r=Object.create(null);for(let[o,i]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof i!="object"||i===null||Array.isArray(i))continue;let s=i;!Number.isSafeInteger(s.count)||s.count<1||typeof s.last_seen!="string"||!s.last_seen.startsWith(o)||(r[o]={count:s.count,last_seen:s.last_seen})}return r}function Hv(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let i of Yv){let s=r[i.alias];if(typeof s!="object"||s===null||Array.isArray(s))continue;let a=s;if(a.canonical!==i.canonical||typeof a.days!="object"||a.days===null||Array.isArray(a.days))continue;let c=mN(a.days,t,o);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function uN(e,t,n){let r=dN(n),o=await Xl(t),i=Hv(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(i))return i;try{await Ja(async()=>{let s=await Xl(t);if(s.alias_usage===void 0)return;let a=Hv(s.alias_usage,r);JSON.stringify(s.alias_usage)!==JSON.stringify(a)&&await te(t,`${JSON.stringify({...s,alias_usage:a},null,2)}
29
+ `)},e,250)}catch{}return i}var Ns=e=>e??null,Ls=async e=>{let t=await A(e),n=zt.join(e,Vv),r=zt.join(e,Wv),o=await Z(n),i=Qv(o),s=await Xl(r),a=Xp();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:Ns(s.last_attempted_flush_at),last_successful_flush_at:Ns(s.last_successful_flush_at),last_failed_flush_at:Ns(s.last_failed_flush_at),last_failed_flush_error:Ns(s.last_failed_flush_error)}},pN=e=>{let t=new Map;for(let n of e)eN(t,n);return[...t.entries()].map(([n,r])=>tN(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},fN=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Ls(t.globalPmRoot),generated_at:S()}),_N=async(e,t)=>{let n=await Ls(t.globalPmRoot);await ef(t.globalPmRoot);let r=await Ls(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:i,queue_drained:i,status:r,generated_at:S()}},hN=async(e,t)=>{let n=oN(e.limit),r=await Z(t.queuePath),o=Qv(r),i=pN(o.entries),s=i.slice(0,n),a=await A(t.globalPmRoot),c=await uN(t.globalPmRoot,t.statePath,a.telemetry.retention_days),m=Object.entries(c).map(([u,p])=>{let f=Object.values(p.days);return{alias:u,canonical:p.canonical,count:f.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:f.map(_=>_.last_seen).sort().at(-1)}}).sort((u,p)=>p.count-u.count||u.alias.localeCompare(p.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:i.length>s.length,stats:s,alias_usage:m,zero_use_aliases:Yv.map(u=>u.alias).filter(u=>c[u]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:S()}},gN=async(e,t)=>Ja(async()=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await $e(t.globalPmRoot,n,"telemetry:clear");let o=zt.join(t.globalPmRoot,HP),i=await G(o);return await BP.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await G(o),queue_exists_after:await G(t.queuePath),state_exists_after:await G(t.statePath),status:await Ls(t.globalPmRoot),generated_at:S()}},t.globalPmRoot),yN={status:fN,flush:_N,stats:hN,clear:gN};async function Zv(e,t){let n=nN(e.subcommand),r=lt(process.cwd());return yN[n](e,{globalPmRoot:r,queuePath:zt.join(r,Vv),statePath:zt.join(r,Wv)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffa50b5b-d99f-5ab4-a70d-cbf12911a0f2")}catch{}})();var ew=20;function vN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ew;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ew:t}function Zl(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let i=Yo(r.recorded_at,o.recorded_at);if(i!==0)return i;let s=r.run_id.localeCompare(o.run_id);return s!==0?s:r.kind.localeCompare(o.kind)}),n=vN();return t.length>n?t.slice(t.length-n):t}async function $s(e){await ae({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=Zl([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3570c976-1b25-501e-b51a-5ecfd1b70c15")}catch{}})();function tw(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function ed(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=tw(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let i of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof i=="number"&&(!Array.isArray(o)||i>=o.length))return{found:!1,value:void 0};let s=Object.getOwnPropertyDescriptor(o,i);if(!s||!Object.hasOwn(s,"value"))return{found:!1,value:void 0};o=s.value}return{found:!0,value:o}}import{spawn as vw}from"node:child_process";import{cp as rd,mkdir as Us,mkdtemp as ww,open as od,readdir as id,rm as Jr,symlink as bw}from"node:fs/promises";import{tmpdir as kw}from"node:os";import V 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]="328c7577-364c-5869-aa92-199e56d2f6a7")}catch{}})();var nw=100;function td(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function wN(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=nw?n:`${n.slice(0,nw-3)}...`}function rw(e){return e.map((t,n)=>`${n+1}. ${wN(t)}`).join("; ")}function bN(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function kN(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function ow(e,t){let n=bN(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let i=[],s=[];for(let a=0;a<e.length;a+=1)kN(e[a],o)&&(s.push(e[a]),i.push(a+1));if(s.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${rw(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:s,selected_indexes:i,selected_count:s.length,skipped_count:e.length-s.length}}if(r==="only-index"){let o=td(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${rw(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="04ea3495-92b7-5518-b06c-a1668d368d66")}catch{}})();var Ds=20*1024*1024,SN=3e3,EN=1e4,AN=5e3,iw=120,TN=new Set(["locks","extensions","runtime"]),CN=new Set(["history","index","search","extensions","locks","runtime"]),IN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],RN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,ON=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,xN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function ad(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function PN(){return ad("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",SN)}function NN(){return ad("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",EN)}function LN(){return ad("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",AN)}function $N(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function FN(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function cd(e){let t=0,n=0,r=0,o=0;for(let i of e){let s=i.execution_context;!s||s.is_pm_command!==!0||(t+=1,s.is_pm_tracker_read_command===!0&&(n+=1),s.mismatch_detected===!0&&(r+=1),s.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function MN(e){let t=e??"project";if(!ct.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function Gs(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(cn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${cn.join(", ")}`,d.USAGE)}function DN(e){return dn(e??"source","--workspace-context")}function Sw(e,t,n){return n?t:dn(e.workspace_context_mode,"linked test")??t}function Ew(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Gs(e.pm_context_mode)}function Aw(e,t){return e==="auto"?t?"tracker":"schema":e}function UN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function GN(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function jN(e,t){let n={};if(!e)return n;for(let r of e){let o=Mr(r,t);if(o)for(let[i,s]of Object.entries(o))n[i]=s}return n}function qN(e,t){if(!e)return[];let n=[];for(let r of e){let o=Dr(r,t);o&&n.push(...o)}return[...new Set(n)]}function KN(e){let t=js(e);return Cr(t).some(n=>ic(n)!==null)}function Tw(e){let t=js(e);return Cr(t).some(n=>{let r=ic(n);if(!r)return!1;let o=y_(r);return o?xN.has(o.subcommand):!1})}function Fs(e){if(e)return __.has(e.subcommand)?qn(e.args,h_)?.subcommand:e.subcommand}function sw(e,t){if(e==="npx"||e==="bunx")return Li(t)?.command;if(e==="pnpm")return Fs(qn(t,m_));if(e==="npm")return Fs(qn(t,u_));if(e==="yarn")return Fs(qn(t,p_));if(e==="bun")return Fs(qn(t,f_))}function Ms(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function nd(e){return!e||!ac(e.command)&&!g_(e.command)?!1:Ni(e.args)==="test-all"}var Cw=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),zN=new Set(["npx","bunx"]);function Iw(e){let t=e.split(" ").filter(s=>s.length>0),n=sc(t);if(n.length===0)return!1;let[r,...o]=n,i=Cw.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0?Iw(o.slice(s+1).join(" ")):!1}return ac(r)||cc(r)?Ni(o)==="test-all":r==="node"&&o.length>0&&cc(o[0])?Ni(o.slice(1))==="test-all":zN.has(r)?nd(Li(o)):r==="pnpm"?nd(lc(o)):r==="npm"?nd(dc(o)):!1}function Rw(e){let t=js(e);return Cr(t).some(n=>Iw(n))}function Ow(e){if(Rw(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function js(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function xw(e){let t=e.split(" ").filter(s=>s.length>0),n=sc(t);if(n.length===0)return!1;let[r,...o]=n,i=Cw.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0&&xw(o.slice(s+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?BN(o):HN(r,o)}function BN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function HN(e,t){return e==="npx"||e==="bunx"?Ms(Li(t)?.command):e==="pnpm"||e==="npm"?Ms((e==="pnpm"?lc(t):dc(t))?.command)||Ms(sw(e,t)):(e==="yarn"||e==="bun")&&Ms(sw(e,t))}function VN(e){if(Rw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function WN(e){return e?e.map(YN):[]}function YN(e){let t=e.trim(),n=fg(t)?ts(de(e,"--add"),"--add"):{command:t},r=he(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Ow(r),{command:r,path:he(n.path),scope:MN(n.scope),timeout_seconds:JN(he(n.timeout_seconds),he(n.timeout)),pm_context_mode:ss(he(n.pm_context_mode),"--add"),workspace_context_mode:dn(he(n.workspace_context_mode),"--add"),env_set:Mr(he(n.env_set),"--add"),env_clear:Dr(he(n.env_clear),"--add"),shared_host_safe:is(he(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:mn(he(n.assert_stdout_contains)),assert_stdout_regex:Hn(he(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:mn(he(n.assert_stderr_contains)),assert_stderr_regex:Hn(he(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:as(he(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:cs(he(n.assert_json_field_equals),"--add"),assert_json_field_gte:ls(he(n.assert_json_field_gte),"--add"),note:he(n.note)}}function he(e){let t=e?.trim();return t&&t.length>0?t:void 0}function JN(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(pe(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function XN(e){return e?e.flatMap(t=>{let n=gg(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);Ow(o)}return n}):[]}function QN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=de(n,"--remove"),i=o.path!==void 0?"path":"command",s=o.path??o.command;if(!s?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:i,value:s.trim()}}return{kind:"either",value:n}}):[]}function ZN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function eL(e){try{e.stdin?.end()}catch{}}function Pw(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=iw?t:`${t.slice(0,iw-3)}...`}function Nw(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function sd(e){try{process.stderr.write(`${e}
30
+ `)}catch{}}function tL(e,t){if(!Nw(t))return null;let n=Pw(e.command),r=Date.now();sd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let i=Date.now()-r;sd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},NN());return o.unref?.(),o}function nL(e,t,n,r){if(!Nw(r))return;let o=Pw(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";sd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${i}${u} command="${o}"`)}async function aw(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=vw("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function rL(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function oL(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await aw(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{aw(r)},PN()),t.forceKillTimer.unref?.()}}function iL(e){return new Promise(t=>{let n=!1,r=null,o=(i,s=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),s&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,s)=>{n||(r=setTimeout(()=>{o({code:i,signal:s},!0)},LN()),r.unref?.())}),e.on("close",(i,s)=>{o({code:i,signal:s})})})}function sL(e,t,n,r,o){return vw(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function cw(e){let t=await od(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Ds),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>Ds}}finally{await t.close()}}async function aL(e,t,n,r,o,i=process.cwd()){let s=Date.now(),a=await ww(V.join(kw(),"pm-linked-test-output-"));try{let c=V.join(a,"stdout.log"),m=V.join(a,"stderr.log"),[u,p]=await Promise.all([od(c,"w"),od(m,"w")]),f;try{f=sL(e,n,u.fd,p.fd,i)}catch(J){throw await Promise.all([u.close(),p.close()]),J}let _=iL(f),h;f.on("error",J=>{h=J.message}),await Promise.all([u.close(),p.close()]),eL(f);let y={heartbeat:tL(r,o),forceKillTimer:null,timedOutTimer:null},g=oL(f,y),v=!1;y.timedOutTimer=setTimeout(()=>{v=!0,g()},t),y.timedOutTimer.unref?.();let{code:b,signal:k}=await _;rL(y);let[T,O]=await Promise.all([cw(c),cw(m)]),L=T.truncated||O.truncated,$=L?`
31
+ [pm linked-test output truncated at ${Ds} bytes per stream; the child process continued to completion]
32
+ `:"",K={stdout:`${T.text}${$}`,stderr:O.text,exitCode:b,signal:k,timedOut:v,maxBufferExceeded:!1,outputTruncated:L,spawnError:h};return nL(r,K,s,o),K}finally{await Jr(a,{recursive:!0,force:!0})}}function cL(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ds} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function lL(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
33
+ `);return IN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>RN.test(n)&&ON.test(n))}function dL(e){return lL(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function mL(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function qs(e){let t=mL();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function lw(e,t){for(let[n,r]of Object.entries(t.env_set))ln.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)ln.has(n.toUpperCase())||delete e[n]}function uL(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function pL(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function fL(e,t,n){return{env_set:jN(e,"--env-set"),env_clear:qN(t,"--env-clear"),shared_host_safe:n===!0}}async function er(e,t,n=!1,r=Us){if(await G(e))try{await ir("seed_linked_test",async()=>{if(await r(V.dirname(t),{recursive:!0}),n){await rd(e,t,{recursive:!0,force:!0});return}await rd(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&Ct(o))return;throw o}}async function dw(e,t,n){await er(ne(n.projectPmRoot),ne(e)),await er(V.join(n.projectPmRoot,"extensions"),V.join(e,"extensions"),!0),await er(ne(n.globalPmRoot),ne(t)),await er(V.join(n.globalPmRoot,"extensions"),V.join(t,"extensions"),!0)}async function mw(e,t){if(!await G(e))return;let n=await id(e,{withFileTypes:!0});for(let r of n){if(TN.has(r.name))continue;let o=V.join(e,r.name),i=V.join(t,r.name);if(r.isDirectory()){await er(o,i,!0);continue}r.isFile()&&await er(o,i)}}async function uw(e,t){let n=await Z(ne(e));if(n===null||await G(za(e)))return;let r=await A(t);await Jr(za(t),{force:!0}),await Jr(ne(t),{force:!0}),await rt({pmRoot:t,filePath:ne(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Zn(e){if(!await G(e))return 0;let t=0,n=await id(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||CN.has(r.name))continue;let o=V.join(e,r.name),i;try{i=await id(o,{withFileTypes:!0})}catch{continue}for(let s of i)s.isFile()&&Wd.some(a=>s.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function _L(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function hL(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function gL(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?qe(e,t):Object.is(e,t)}function yL(e,t,n){let r=[];r.push(...pw("stdout",t,e.assert_stdout_contains)),r.push(...fw("stdout",t,e.assert_stdout_regex)),r.push(...pw("stderr",n,e.assert_stderr_contains)),r.push(...fw("stderr",n,e.assert_stderr_regex)),r.push(...vL(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(o)){let u=ed(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=hL(m);gL(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,m]of Object.entries(i)){let u=ed(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<m&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${m}, actual ${u.value})`)}return r}function pw(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function fw(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(i){r.push(`${e} regex assertion is invalid: /${o}/ (${i instanceof Error?i.message:String(i)})`)}return r}function vL(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var wL=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],bL=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function kL(e,t){let n=`${e}
34
+ ${t}`;for(let r of wL)if(r.regex.test(n))return{code:r.code};return null}function SL(e,t){let n=`${e}
35
+ ${t}`;return bL.some(r=>r.test(n))}function _w(e){let t=js(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Cr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&xw(n))}function EL(e){return{root:e,schemaProjectPmPath:V.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:V.join(e,"schema","global"),trackerProjectPmPath:V.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:V.join(e,"tracker","global"),workspaceSnapshotRoot:V.join(e,"workspace","project"),workspaceIsolatedRoot:V.join(e,"workspace","isolated")}}function AL(e,t,n){return e.some(r=>Sw(r,t,n)==="snapshot")}async function TL(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await Us(V.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await rd(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let i=V.relative(t,o);return i?!i.split(V.sep).some(s=>n.has(s)):!0}});let r=V.join(t,"node_modules");await G(r)&&await bw(r,V.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function CL(e,t){let n=V.join(e,".agents"),r=V.join(n,"pm");await Us(n,{recursive:!0}),await Jr(r,{recursive:!0,force:!0}),await bw(t,r,process.platform==="win32"?"junction":"dir")}async function IL(e,t=Nr,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function RL(e,t,n){t&&(await dw(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await dw(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await mw(t.projectPmRoot,e.trackerProjectPmPath),await mw(t.globalPmRoot,e.trackerGlobalPmPath),await uw(t.projectPmRoot,e.trackerProjectPmPath),await uw(t.globalPmRoot,e.trackerGlobalPmPath)))}function OL(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&Tw(o),s=n?.autoPmContext===!0&&i?"auto":Ew(r,t,n?.overrideLinkedPmContext===!0);return Aw(s,i)==="tracker"})}async function xL(e,t){return{sourceProjectItemCount:t?await Zn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Zn(t.globalPmRoot):0,schemaProjectItemCount:await Zn(e.schemaProjectPmPath),schemaGlobalItemCount:await Zn(e.schemaGlobalPmPath),trackerProjectItemCount:await Zn(e.trackerProjectPmPath),trackerGlobalItemCount:await Zn(e.trackerGlobalPmPath)}}function PL(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,s=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":s;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:s,source_workspace_root:a,trust:e.trust}}async function NL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Gs(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?KN(n):!1,o=r&&n?Tw(n):!1,i=e.options?.autoPmContext===!0&&o,s=i?"auto":Ew(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Aw(s,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await CL(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await mc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await mc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:PL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:s,effectivePmContextMode:a,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function hw(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Xr(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function LL(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function $L(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return LL(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function FL(e){if(!e.linkedTest.command)return hw(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=VN(e.linkedTest.command);return t?hw(e.linkedTest,e.executionContext,t):null}function ML(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Xr(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Xr(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function DL(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=GN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Xr(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function UL(e){let t=FL(e);if(t)return t;let n=$L(e);if(n)return n;let r=ML(e);if(r)return r;let o=DL(e);return o||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!UN(e.linkedTest)?Xr(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function GL(e){let t=pL(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return lw(n,e.runtimeDirectives),lw(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&uL(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Er]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Er]="read_only"),n}function jL(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function gw(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function qL(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:_L(e.execution),failure_category:dL(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:cL(e.execution,e.timeoutMs)}}function KL(e){if(e.options?.failOnEmptyTestRun===!0||_w(e.linkedTest.command??"")){let n=kL(e.execution.stdout,e.execution.stderr);if(n)return gw({...e,emptyRunSignal:n});if(_w(e.linkedTest.command??"")&&!SL(e.execution.stdout,e.execution.stderr))return gw({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=yL(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Xr(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):jL(e.linkedTest,e.executionContext,e.execution)}async function zL(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await aL(t,n,GL(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?KL({...e,execution:r}):qL({...e,execution:r,timeoutMs:n})}async function ld(e,t,n){let r=[],o=await ww(V.join(kw(),"pm-linked-test-")),i=EL(o),s=Gs(n?.pmContext),a=DN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=fL(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=w_(),f=OL(e,s,n),_=AL(e,a,n?.overrideLinkedWorkspaceContext===!0),h=await v_(p);try{await IL(i,Nr,f),await Us(i.workspaceIsolatedRoot,{recursive:!0}),await RL(i,u,f),_&&await TL(i,p);let y=await xL(i,u);for(let g=0;g<e.length;g+=1){let v=e[g],b=Sw(v,a,n?.overrideLinkedWorkspaceContext===!0),k=await NL({linkedTest:v,layout:i,counts:y,sourceRoots:u,runLevelPmContextMode:s,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:b,currentSourceRef:h,sourceWorkspaceRoot:p}),T=UL({linkedTest:v,executionContext:k.executionContext,runLevelPmContextMode:s,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await zL({linkedTest:v,index:g,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Jr(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function BL(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await q(n,t,r.id_prefix,r.item_format,o);if(!i)throw new l(`Item ${t} not found`,d.NOT_FOUND);let s=await se(i,{schema:r.schema});return{itemId:i.id,tests:s.document.metadata.tests??[],testRuns:s.document.metadata.test_runs??[],changed:!1,removed:0}}function HL(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function VL(e,t){let n=[...e];for(let r of t)n.some(o=>HL(o,r))||n.push(r);return n}function WL(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,s)=>r.has(s+1)?!1:!t.some(a=>a.kind==="command"?i.command===a.value:a.kind==="path"?i.path===a.value:i.command===a.value||i.path===a.value));return{tests:o,removed:e.length-o.length}}function YL(e,t,n,r){return WL(VL(e,t),n,r)}function JL(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function XL(e){if(JL(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function QL(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:s,removes:a,removeIndexes:c}=e;if(s.length===0&&a.length===0&&c.length===0)return BL({id:t,pmRoot:r,settings:o,typeToFolder:i});let m=0,u=await ae({pmRoot:r,settings:o,id:t,op:s.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=YL(f,s,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:qe(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function ZL(e,t){XL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:td(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?ow(t,n):void 0,o=e.timeout===void 0?void 0:pe(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:Gs(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function e$(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await ld(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:lt(process.cwd())}})}function t$(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=cd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function n$(e){let t=FN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=S(),i=Yr(e.options.measure,o);return{run_id:$N("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:i.length>0?i:void 0,executions:e.runResults.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}}async function r$(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:s,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!i)return;let m=n$({options:t,runStartedAt:i,runResults:s,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:m,receipt:{recorded:!1,reason:"tracking_disabled",run_id:m.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await $s({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),{entry:m,receipt:{recorded:!0,reason:"recorded",run_id:m.run_id}}}catch(u){return c.push(`test_result_tracking_failed:${o}:${u instanceof Error?u.message:String(u)}`),{entry:m,receipt:{recorded:!1,reason:"write_failed",run_id:m.run_id}}}}function yw(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),s=e.metricBelow.slice(o+1).trim(),a=Number(s);if(o<=0||i.length===0||s.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=Uv(t,i,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Gv(t,e.metricDiff)}}async function o$(e,t,n){if(e.acknowledgeLinkedTests===!0)return b_(t,n,S())}function i$(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:s,recording:a,measurementProjection:c}=e;return{ok:n.every(m=>m.status!=="failed")&&i!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:r,selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:s.length>0?s:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Ks(e,t,n){let r=Lt(),o=E(process.cwd(),n.path);await I(o);let i=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Yr(t.measure,"validation"),yw(t,[],void 0);let s=x(i,R()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...WN(a),...XN(c)],p=await Kn(u,C(t.author,i.author_default),S())??[],f=QN(m),_=ZN(t.removeIndex),h=await QL({id:e,options:t,pmRoot:o,settings:i,typeToFolder:s.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=ZL(t,h.tests),g=await o$(t,o,h.tests),v=t.run===!0?S():void 0,b=await e$({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests}),k=qs(b),T=t.run===!0&&t.failOnSkipped===!0&&b.some(J=>J.status==="skipped"),O=t$(t,y.runSelection,b);g&&O.push(`linked_test_trust_acknowledged:${g.acknowledged}`);let L=await r$({options:t,pmRoot:o,settings:i,itemId:h.itemId,runStartedAt:v,runResults:b,failOnSkippedTriggered:T,warnings:O}),$=L?.receipt.recorded?Zl([...h.testRuns,L.entry]):h.testRuns,K=yw(t,$,L?.entry);return i$({item:h,runResults:b,failureCategories:k,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:O,recording:L,measurementProjection: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]="e3e3a1d4-4552-5f3c-9b02-c33ae72ea32b")}catch{}})();var s$=(e,t)=>{if(e===void 0)return;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},a$=e=>{if(e===void 0)return;let t=pe(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Lw=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},c$=e=>e instanceof Error?e.message:String(e),l$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},d$=e=>e.trim().replaceAll(/\s+/g," "),m$=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),u$=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),p$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},f$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},zs=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),$w=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),_$=e=>typeof e=="number"?e:void 0,h$=e=>{let t={assert_stdout_contains:zs(e.assert_stdout_contains),assert_stdout_regex:zs(e.assert_stdout_regex),assert_stderr_contains:zs(e.assert_stderr_contains),assert_stderr_regex:zs(e.assert_stderr_regex),assert_stdout_min_lines:_$(e.assert_stdout_min_lines),assert_json_field_equals:$w(e.assert_json_field_equals),assert_json_field_gte:$w(e.assert_json_field_gte)};return JSON.stringify(t)},g$=e=>{let t=dd(e.command);return t!==void 0?`command:${e.scope}:${d$(t)}`:`path:${e.scope}:${dd(e.path)??""}`},Fw=e=>{let t=m$(e.env_set),n=u$(e.env_clear),r=p$(e.pm_context_mode),o=f$(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",s=h$(e);return`${g$(e)}:${t}:${n}:${r}:${o}:${i}:${s}`},y$=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,v$=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},w$=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Bs=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
36
+ `)}catch{}},b$=async(e,t,n)=>{let r=[],o=0;for(let i of e){let s=await Ks(i.id,{run:!1},{...t,path:n});o+=s.tests.length,r.push({item:i,tests:s.tests})}return{itemTests:r,linkedTests:o}},k$=async e=>{let t=F(e.settings.schema),n=x(e.settings,R()),r=s$(e.options.status,t),o=Lw(e.options.limit,"--limit"),i=Lw(e.options.offset,"--offset")??0,a=(await fe(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},S$=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Fw(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,y$(t.get(o),r.timeout_seconds))}return t},E$=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Fw(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await ld(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],i=0,s=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[i];return i+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=v$(s),c=qs(s),m=await C$(e,a,s,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:s,failure_categories:c}}},A$=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),T$=e=>e?!0:void 0,C$=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=A$(t,r.options);await $s({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:S(),recorded_at:S(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:T$(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${c$(o)}`]}return[]},I$=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},dd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},R$=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:lt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:S$(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:l$(),trackingAttempt:I$(),trackingResumedFrom:dd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),O$=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:qs([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},x$=async(e,t,n)=>{for(let[r,o]of e.entries()){Bs(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let i=await E$(o,t);w$(n.failureCategories,i.failureCategories),n.passed+=i.passed,n.failed+=i.failed,n.skipped+=i.skipped,n.trackingWarnings.push(...i.trackingWarnings),n.results.push(i.result),Bs(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${i.failed===0?"passed":"failed"} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`)}},P$=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=cd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},N$=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),L$=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),$$=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await k$({pmRoot:n,settings:r,options:e}),i=a$(e.timeout),s=S(),a=await b$(o.filteredItems,t,n);return Bs(e,L$({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:s}},F$=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},Mw=async(e,t)=>{let n=await $$(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=O$(e,n.linkedTests,n.filteredItems),i=R$({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await x$(n.itemTests,i,r),P$(e,r);let s=F$({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Bs(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),N$({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="419a061f-e181-5b18-9e3a-d22cc5aff416")}catch{}})();function Dw(e,t,n){let r;if(typeof e.lines=="string")r=Ri(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=Ri(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6f4c40f-50cf-568f-8a45-860ac4be3c97")}catch{}})();function Pe(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b86373f-26a3-5893-95dc-e794fcc1afa1")}catch{}})();function M$(e){let t=w(e.args,"subcommand")??Pe(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ge(n)}}function D$(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=wn({list:()=>Sf(t.global),show:()=>Ef(r,t.global),"show-status":()=>Af(r,t.global),"list-fields":()=>If(t.global),"show-field":()=>Rf(r,t.global),"remove-type":()=>vf(r,{author:o,force:i},t.global),"remove-field":()=>Cf(r,{author:o,force:i},t.global),"remove-status":()=>kf(r,{author:o,force:i},t.global),"apply-preset":()=>Of(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function U$(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Tf(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:s===void 0?void 0:ge(s),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:ge(a),author:r,force:o},t.global)}function G$(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.role??t.options.role;return bf(n,{role:s===void 0?void 0:ge(s),alias:i,description:w(t.args,"description")??w(t.options,"description"),order:Fe(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function j$(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return yf(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:i,author:r,force:o},t.global)}function q$(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,s=w(t.args,"to")??Pe(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:s}:n==="rename-field"?{kind:"rename-field",from:r??"",to:s,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:s};return hf(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function Uw(e){let t=M$(e);Fp(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Tn.find(o=>o===t.subcommand);if(n)return _f(n,t.name,{definition:e.args.definition??e.options.definition,policy:w(e.args,"policy")??w(e.options,"policy"),message:w(e.args,"message")??w(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=D$(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return q$(t);if(t.subcommand==="add-field")return U$(t);if(t.subcommand==="add-status")return G$(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?xf({minCount:Fe(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):j$(t);throw Te({command_path:"schema",token:t.subcommand,allowed:gf,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d5136ee1-7446-5fbf-b782-bc58b5323c64")}catch{}})();function Hs(e){return w(e.args,"target")??w(e.options,"target")}function we(e,t=e.options){return e.id??Pe(t,"id")}async function K$(e){let t=Rn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Cc(await ht(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function z$(e){let t=Pe(e.args,"query"),n=Rn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Cc(await Or(t,n,e.global),n)}async function B$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await jt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function H$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Se(await Bc(we(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function V$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await it(we(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function W$(e){let t=zi(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),bh(we(e),t,e.global)}function Gw(e,t){return Wf(Dw(e.options,t,Fe),e.global)}function Y$(e){let t=ge(e.options.lookupPath);if(t&&t.length>0)return Gw(e,t);let n=we(e);return e.options.discover===!0?oc(n,Ei(e.options),e.global):Vf(n,Ar(e.options),e.global)}function J$(e){return Zv({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Df(e.args,e.options)},e.global)}function X$(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Tr(e.global,t)}function Q$(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Kh(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function Z$(e){let t=e.options;return x_(O_(t),e.global)}function eF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function tF(e){let t=w(e.args,"subcommand")??Pe(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=_e(e.args,e.options),i=await by({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:nF(e),reorderTo:eF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&$f(e.args)&&(i.mutation_receipt=As(i,void 0)),t==="show"?i:Se(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function nF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function rF(e){let t=w(e.args,"subcommand")??Pe(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),i=wn({list:()=>Fy(),show:()=>My(r),lint:()=>Dy(r),apply:()=>Uy(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!i)throw Te({command_path:"profile",token:t,allowed:$y,exit_code:64});return i()}async function oF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options);return Se(await ng(we(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function iF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options);return Se(await Ty(Ci(n),e.global),{changedFields:t})}async function sF(e){let{changedFields:t,runnerOptions:n}=_e(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Se(await ug(Ti(o),e.global),{changedFields:t})}async function aF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=_e(e.args,e.options),o=w(r,"target")??Pe(e.args,"target");return Se(await sn(we(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function cF(e){let t={...e.args,...e.options};return Yf(Pe(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),qf(t),e.global)}function lF(e){return zf(E(process.cwd(),e.global.path),{...e.args,...e.options})}var jw={init:e=>Nr(w(e.args,"prefix"),e.global,e.options),context:e=>fc(Rn("context",e.options),e.global),next:e=>Rr(Rn("next",e.options),e.global),eval:vv,events:wv,merge:bv,workspace:kv,meet:xs,event:xs,remind:xs,list:K$,get:e=>{let t=we(e);return hc(t,e.global,Rn("get",e.options,[t]))},search:z$,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ge(e.options.status);return rc(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:w(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Fe(e.options.limit,"limit")})},create:B$,copy:H$,focus:e=>ol(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:V$,"item-reopen":cy,restore:aF,claim:iy,release:ay,"start-task":e=>_n(e,"start_task"),"pause-task":e=>_n(e,"pause_task"),"close-task":e=>_n(e,"close_task"),close:sy,comments:W$,notes:e=>Cy(we(e),zi(e.options),e.global),learnings:e=>tg(we(e),zi(e.options),e.global),files:Y$,docs:e=>Hf(we(e),Ar(e.options),e.global),test:e=>Ks(we(e),e.options,e.global),"test-all":e=>Mw(e.options,e.global),telemetry:J$,validate:e=>$i(e.options,e.global,{runUpdate:(t,n,r)=>it(t,n,r)}),health:X$,assurance:e=>k_(e.args,e.options,e.global),contracts:e=>wc(e.options,e.global),config:Q$,activity:Z$,aggregate:e=>_c(e.options,e.global),extension:e=>Un(Hs(e),e.options,e.global),package:e=>Un(Hs(e),e.options,e.global),install:e=>Un(Hs(e),{...e.options,install:!0},e.global),upgrade:e=>E_(Hs(e),e.options,e.global),delete:e=>rl(we(e),e.options,e.global),deps:e=>Bf(we(e),e.options,e.global),graph:cF,"files-discover":e=>oc(we(e),e.options,e.global),"files-lookup":e=>Gw(e,ge(e.options.paths)),history:e=>P_(we(e),e.options,e.global),"history-redact":e=>eg(we(e),e.options,e.global),"history-repair":Yh,"history-compact":Jh,"history-attest":e=>A_(e.options,e.global),"history-author-acknowledge":lF,plan:tF,schema:Uw,profile:rF,stats:e=>Yl(e.global,Sv(e.options)),append:oF,"update-many":iF,"close-many":sF,gc:e=>S_(e.global,e.options)};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8137f8b-745a-5ef5-9e7e-14b7d032c1ea")}catch{}})();var dF=new Map;function md(){dF.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c84b11c-502f-5c33-a757-5757402357b4")}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]="b841f903-6276-5067-842f-6a6bff114cec")}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]="4277a72c-f012-55d2-9e18-c9a836d829d6")}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]="aba4af26-98d3-53aa-8b23-1be7c90a38d1")}catch{}})();function qw(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5b106ed0-ef19-58a4-a7d0-bd0988482f58")}catch{}})();var zw=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:ip().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],Kw=new Map;for(let e of zw){Kw.set(e.id,e);for(let t of e.aliases)Kw.set(t,e)}function ud(){return zw.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a7cf539-2663-5265-90e8-c2aa9926a62a")}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]="be171aef-09e7-5f87-9605-1d47ca665440")}catch{}})();var k5=[...no],S5=[...ro],pd=new Set(Jt.filter(e=>e.hidden).map(e=>e.alias)),Bw=op("full").filter(e=>!e.includes(" ")&&!pd.has(e)),mF=N(fo),uF=N(_o),pF=N(ko),fF=N(Co),Hw=ur("restore",Rt("restore")),Vw=ur("history-attest",Rt("history-attest")),_F=N(Io),hF=N(Wm),gF=N(Ym),yF=N(To),vF=N(Po),wF=N(Ro),bF=N(Oo),kF=N(bo),fd=[...new Set(ke.map(e=>e.canonical_argv[0]))],Ww=[...new Set(ke.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],E5=new Set(uo.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),Yw=ke.filter(e=>e.canonical_argv[0]==="history"),SF=Yw.map(e=>e.canonical_argv[1]).join(" ");var EF=Yw.map(e=>({...e,flags:N(Rt(e.alias))})),AF=N(ho),TF=N(go,!1),CF=N(xo),IF=N(dr),RF=N(mr),OF=N(Fo),xF=N(Lo),PF=N(Eo),NF=N($o),LF=N(No),$F=N(Mo),FF=N(So),MF=N(Ao),DF=N(vo),UF=N(Do),GF=N(yo),_d=`${Tn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var jF=N(Uo),qF=`${jF} bash zsh fish`,hd=Ws(ud()),Vs="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",gd=`${Vs} upgrade`,KF=N(wo),zF=N(cr),BF=N(lr);var HF=N(Rt("close")),VF=N(Rt("close-task")),WF=N(Rt("release")),YF=N(Rt("claim"));var Jw=po.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),yd=[...Wo].join("|"),vd=[...Wo].map(e=>`${e}=*`).join("|"),wd=[...Jw.split(" ").filter(e=>!Wo.has(e)),"-h","-V"].join("|");function Ws(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2dba61cf-0757-5b46-b86c-e5b7a1c733ae")}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]="1cf1ab58-6aaf-5d9b-9681-0a070119c791")}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]="818bb54f-06ad-587f-86d6-4eaee9e4966c")}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]="c1fb3981-3bae-5f63-861a-ee689a9ffd36")}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]="2c2a4576-a5d8-57c1-84e8-ca8b9019c84e")}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]="e7f8a7ea-3ec2-521b-ad52-45b655208f06")}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]="f42d8a66-b4c0-5281-b5ef-fdc0ea503f58")}catch{}})();var nb=Symbol("pm.active-extension-host-context");function Ge(e){return{fullChangedFields:!0,options:e}}var U=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[nb]=!0,n}run(t,n={}){return rb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return fh(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Za(await this.list(Qa(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...Ge(Ut(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:Ut(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ge(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ge(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ge(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ge(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ge(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ge(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ge(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ge(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Ge(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ge(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ge(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ge(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function oM(e={},t={}){return new U(t).context(e)}function iM(e={},t={}){return new U(t).list(e)}function sM(e={},t={}){return new U(t).listAllComplete(e)}function aM(e,t={},n={}){return new U(n).search(e,t)}function cM(e,t={},n={}){return new U(n).get(e,t)}function lM(e={},t={}){return new U(t).next(e)}function dM(e={},t={}){return new U(t).aggregate(e)}function mM(e,t={},n={}){return new U(n).comments(e,t)}function uM(e,t={},n={}){return new U(n).notes(e,t)}function pM(e,t={},n={}){return new U(n).learnings(e,t)}function fM(e,t={},n={}){return new U(n).files(e,t)}function _M(e,t={},n={}){return new U(n).filesDiscover(e,t)}function hM(e,t={},n={}){return new U(n).docs(e,t)}function gM(e,t={},n={}){return new U(n).deps(e,t)}function yM(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function vM(e,t,n={},r={}){return new U(r).append(e,t,n)}function wM(e={},t={}){return new U(t).create(e)}function bM(e,t={},n={}){return new U(n).update(e,t)}function kM(e,t,n={},r={}){return new U(r).reopen(e,t,n)}function SM(e,t,n={},r={}){return new U(r).close(e,t,n)}function EM(e,t={},n={}){return new U(n).claim(e,t)}function AM(e={},t={}){return new U(t).claimNext(e)}function TM(e,t={},n={}){return new U(n).release(e,t)}function CM(e,t={},n={}){return new U(n).copy(e,t)}function IM(e,t={},n={}){return new U(n).delete(e,t)}function RM(e,t,n={},r={}){return new U(r).restore(e,t,n)}function OM(e,t={},n={}){return new U(n).focus(e,t)}var eb=Fu(),xM=new rM;function Ys(){Aa(Jd()),Ta(Xd()),Ca(Qd()),Ia(Zd()),Ra(em()),Oa(tm()),xa(nm())}async function PM(e,t,n,r){return Mu(()=>t===void 0?eb.read(()=>tb(e,n,r)):eb.write(()=>LM(t,()=>tb(e,n,r))))}async function tb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Ys(),kc({pmRoot:r},()=>n(null));if(!await G(ne(r)))return Ys(),n(null);let o=null,i;try{let s=await A(r),a=await sr({pmRoot:r,settings:s,cwd:t,noExtensions:!1}),c=await ar({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},Aa(c.hooks),Ta(c.commands),Ca(c.parsers),Ia(c.preflight),Ra(c.services),Oa(c.renderers),xa(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(s){Ys(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",s)}try{return await kc({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Ys(),i&&await ha(i.loadResult,i.activationResult).catch(()=>{})}}async function NM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let i=Gn(e),a=o.registrations.commands.find(u=>Gn(u.action)===i)?.command??o.commands.handlers.find(u=>Gn(u.command)===i)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension",m=await Vo({command:Ai(a),args:ge(n.args??t.args),options:nc(t,n),global:r,pm_root:o.pmRoot,sdk:lh(o.pmRoot,U.forActiveExtensionHost({pmRoot:o.pmRoot,author:c}),c,Ai(a))});if(!m.handled){let u=m.warnings.length>0?` (${m.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${u}`,d.USAGE)}return m.result}async function LM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function $M(e){let t=Pe(e,"action"),n=Gn(t),r=wn(hh,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...fa(e.options)}),o==="package"&&(i.options={...fa(i.options),vocabulary:"package"}),{action:o,args:i}}async function rb(e){let t=$M(e),n=ec(t.args),r=Gf(t.action),o=w(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[Tc]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(i,n.path));try{return t.action==="history-attest"?await bd(t.action,t.args,n,null):e[nb]===!0||xM.getStore()===!0?await bd(t.action,t.args,n,null):await PM(n,o,i,s=>bd(t.action,t.args,n,s))}finally{r&&md()}}async function bd(e,t,n,r){let o=tc(t,e);$a(e,o),qu(e,o);let i={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},s=wn(jw,e),a=s?await s(i):await NM(e,t,o,n,r);if(e==="history-attest")return a;{o.resolvedOutputFormat="json";let c=Hu(e,o,a);return await ah(E(process.cwd(),n.path),c),c}}var FM={closeManyOptionsFromFlat:Ti,extensionOptionsFromArgs:nc,globalOptions:ec,mutationListOptions:jf,normalizeActionName:Gn,normalizeCommandPath:Ai,normalizeMcpUpdateOptions:Kf,normalizeMcpOptionsArrays:Uf,optionsWithAuthor:tc,readRequiredString:Pe,readScalarString:Ff,readScalarStringAllowBlank:Mf,readStringArray:ge,updateManyOptionsFromFlat:Ci,withAddNoteOption:Ar,withFilesDiscoveryOptions:Ei,withMutationCompaction:_e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=FM);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3eaa41f7-77a1-5838-8a2f-2ab6a49c21ef")}catch{}})();export{On as AGENT_PROVENANCE_DIMENSIONS,fp as BASELINE_ITEM_FORMAT_VERSION,rk as BUILTIN_AGENT_PROVENANCE_ADAPTERS,pr as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,no as BUILTIN_ITEM_TYPE_VALUES,oo as CONFIDENCE_TEXT_VALUES,_p as CURRENT_ITEM_FORMAT_VERSION,Vt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,kn as ISSUE_SEVERITY_VALUES,$d as ITEM_TYPE_VALUES,Sc as PM_CLI_EXPECTED_ERROR_NAME,Kb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,jb as PM_READ_OUTPUT_DIMENSIONS,qb as PM_READ_OUTPUT_OPTION_FLAGS,Na as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,bn as RISK_VALUES,gk as SEMANTIC_ATTRIBUTION_LIMITS,ro as STATUS_VALUES,nk as agentSessionEnvironment,dM as aggregate,Vl as analyzeAgentProvenanceDescriptorCoverage,Qb as analyzeSdkCliParameterCompleteness,vM as append,Bb as applyReadOutputDimensions,Yb as applyReadOutputSessionReferences,Jb as attachReadOutputSessionReceipt,Zb as boundAgentEpisodeIdentity,tt as canonicalDocument,EM as claim,AM as claimNext,yp as classifyItemFormatVersion,SM as close,mM as comments,oM as context,CM as copy,wM as create,ch as createPmCliExpectedError,Gb as decodeReadOutputContinuationCursor,IM as deleteItem,gM as deps,dk as detectAgentIdentity,pk as detectHarnessIdentity,mk as diagnoseAgentIdentity,hM as docs,hp as effectiveItemFormatVersion,qw as emptyImportedDocument,Ub as encodeReadOutputContinuationCursor,gP as evaluateSemanticAttributionCoverage,_k as explainSourceTraceability,fM as files,_M as filesDiscover,OM as focus,cM as get,yM as graph,yP as groupHistoryByEpisode,ry as isAlreadyClaimedError,qi as isPmCliExpectedError,Hb as isReadOutputBudgetExceeded,pM as learnings,iM as list,ik as listAgentProvenanceAdapters,sM as listAllComplete,lM as next,ak as normalizeAgentProvenanceAdapterValue,gp as normalizeItemFormatVersion,Ke as normalizeItemId,ee as normalizeStatusInput,uM as notes,S as nowIso,Wb as parseReadOutputSession,Ri as parseSourceLineRange,ei as readAuthorEnvironment,Xb as readOutputSessionRemainingTokens,uc as recordClaimSemanticAttribution,Mi as recordFocusSemanticAttribution,pc as recordReleaseSemanticAttribution,sk as registerAgentProvenanceAdapters,ok as registerHarnessSignalDescriptors,TM as release,kM as reopen,ek as resolveAgentSessionContextFromSignals,fk as resolveAuthorIdentity,Pv as resolveHistoryEpisodeGroupIdentity,zb as resolveReadOutputDimensions,Vb as resolveReadOutputEncoding,La as resolveReadOutputSurface,hk as resolveSemanticLineageIds,RM as restore,rb as runAction,tk as runWithAgentSessionContext,ck as runWithHarnessDetectionSignals,lk as runWithWorkspaceHarnessSignalDescriptors,aM as search,yk as semanticAttributionAffinity,He as serializeItemDocument,hP as summarizeAgentModelProvenance,Wl as summarizeAgentProvenance,bM as update,$a as validateReadOutputOptions,uk as writeAuthorEnvironment};
37
37
  //# sourceMappingURL=sdk-core.js.map