@unbrained/pm-cli 2026.11.2 → 2026.11.4
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +24 -0
- package/dist/cli/error-guidance.d.ts +23 -35
- package/dist/cli/error-guidance.js +4 -3
- package/dist/cli/expected-revisions.d.ts +55 -0
- package/dist/cli/expected-revisions.js +2 -0
- package/dist/cli/main.js +2 -2
- package/dist/cli/runtime/field-route-retry.d.ts +15 -0
- package/dist/cli/runtime/field-route-retry.js +2 -0
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-3A4NVHYS.js → chunk-2GW662DP.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-3OXQGGRD.js +115 -0
- package/dist/cli-bundle/chunks/chunk-5BVZ32G7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5S6RT5LX.js +9 -0
- package/dist/cli-bundle/chunks/chunk-5Z6LWFDL.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-RGHLQGEX.js → chunk-6T2V3UIK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JRXD7SIL.js → chunk-7PGNAHNW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7RCI7AAA.js +20 -0
- package/dist/cli-bundle/chunks/chunk-AQ5UHHQS.js +2 -0
- package/dist/cli-bundle/chunks/chunk-BK2XAQVC.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ABFFRQRO.js → chunk-BRIPGUAO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-BWAXA6S4.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-HOGKWJU5.js → chunk-CERNIZLB.js} +66 -66
- package/dist/cli-bundle/chunks/chunk-DSCFJTHB.js +122 -0
- package/dist/cli-bundle/chunks/{chunk-VEOFWE32.js → chunk-L4BKTPJ6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NGRPD3ZO.js → chunk-NPEDFOVQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J3JM36EH.js → chunk-O4ZLEN4T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-533L6D2N.js → chunk-ODMJ3HIB.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-KJLGBLR3.js → chunk-QN7VCOUU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QQHMNUZT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-D52QQ7LP.js → chunk-RSAN2YUU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-SRDO2NJU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-T56MB6SF.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TX2W6G37.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-GK2CHAT3.js → chunk-UJMQP2HP.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-IEJ2QOW3.js → indexed-receipt-blobs-I6RQGD6Y.js} +2 -2
- package/dist/cli-bundle/chunks/item-revision-UAZOBP2Q.js +2 -0
- package/dist/cli-bundle/chunks/item-transaction-N5F4LXYV.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-QZQI2NN5.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NZTK3AXA.js → register-list-query-P3NOKQUA.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-2OFAMOVH.js → register-mutation-A6I5K5N6.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-SPKB3TNM.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-ZZRHJ4IS.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-UTCEZBFT.js → settlement-hook-JHXLUBEN.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-VLI4OBVX.js → stage-L3T725DS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5NGNO54M.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PCCZ72C3.js → chunk-A2246ZM7.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-B6U44WPW.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-BAW3DGQO.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-BHNY3KPJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-745IDMTD.js → chunk-C7UX2ZI3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CBG67HUP.js +23 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NJFMG3IK.js → chunk-CO2DNPH7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CXTDEQ3N.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-FEPE2CE4.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-FFO7RBLN.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QNXXOFLQ.js → chunk-FXFDVM5O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QVFE5LIX.js → chunk-G6ERMFJ5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MQVBWFJF.js → chunk-IDAYTYNN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-J3YOATXR.js +80 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3UD6F2KQ.js → chunk-J6FDCAMH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-J7M52SCZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-JQS7TYQ6.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-MEJKELWC.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-PMKR4MJI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-PNPYQDHU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Q4OIRSKL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-I4Z2SCV5.js → chunk-QEVJ3Y67.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Q23K6WLV.js → chunk-SDLIUZEL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-TFYTTDAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-W3CSX6GI.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-B6OOKKOX.js → chunk-Y5GOUUYJ.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FT3KF6VJ.js → indexed-receipt-blobs-7XGVHYAO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-L6GVT42D.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-GYGP264N.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-UWTH56OD.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-KMIBD4F2.js → settlement-hook-H56537UV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-6B3O2GZ6.js → stage-WRSNJ7VI.js} +2 -2
- package/dist/cli-bundle/main.js +30 -29
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +5 -5
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/config/positional-value.d.ts +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/item-fields.d.ts +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/schema/runtime-field-values.d.ts +30 -0
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/command-types.d.ts +7 -0
- package/dist/core/shared/error-details.d.ts +98 -0
- package/dist/core/shared/error-details.js +2 -0
- package/dist/core/shared/errors.d.ts +37 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-mutation-precondition.d.ts +70 -6
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/mcp/server.js +2 -2
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +11 -0
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/config.d.ts +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +1 -1
- package/dist/sdk/errors.d.ts +6 -2
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/history/salvage.js +3 -3
- package/dist/sdk/history-compact.d.ts +7 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-repair.d.ts +2 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +4 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +10 -2
- package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close-many.d.ts +11 -2
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.d.ts +15 -0
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/core-field-recovery.d.ts +26 -0
- package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/item-revision.d.ts +162 -0
- package/dist/sdk/lifecycle/item-revision.js +2 -0
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.d.ts +52 -0
- package/dist/sdk/lifecycle/start-blockers.js +2 -0
- package/dist/sdk/lifecycle/task-composition.d.ts +11 -0
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.d.ts +11 -2
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/declared-blockers.d.ts +16 -0
- package/dist/sdk/query/declared-blockers.js +2 -0
- package/dist/sdk/query/get.d.ts +7 -0
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/runtime-input.d.ts +12 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.d.ts +11 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/entry.d.ts +5 -0
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution.d.ts +1 -2
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/linked-command-detection.d.ts +10 -0
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/update.d.ts +2 -0
- package/dist/sdk/test/update.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +17 -6
- package/dist/sdk/workspace-transaction.js +1 -1
- package/dist/types.d.ts +6 -0
- package/dist/types.js +1 -1
- package/docs/COMMANDS.md +91 -0
- package/docs/CONFIGURATION.md +1 -0
- package/docs/EXTENSIONS.md +2 -2
- package/docs/LINKED_TEST_EDITS.md +38 -5
- package/docs/SDK.md +185 -1
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +111 -111
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +15 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3ZQQVJT2.js +0 -20
- package/dist/cli-bundle/chunks/chunk-4HW253W2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4OELCF3O.js +0 -2
- package/dist/cli-bundle/chunks/chunk-BFZUJ5QP.js +0 -115
- package/dist/cli-bundle/chunks/chunk-DAZFCSDV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-EN27ZQSV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-K46GDAKX.js +0 -6
- package/dist/cli-bundle/chunks/chunk-OJR2YGXF.js +0 -31
- package/dist/cli-bundle/chunks/chunk-QHHFXNSQ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-ZNWDYDFF.js +0 -129
- package/dist/cli-bundle/chunks/item-transaction-JHPBH6N7.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-QUNQZCZ5.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-RFMM5KZ6.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-6B6Q7M5L.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4NVPDZLX.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-4UUE3YXZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5UDDRPYR.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EJJWOFP5.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-FUGYXUUL.js +0 -80
- package/dist/cli-bundle/focused-chunks/chunk-HMXVTWIV.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-JLN5CFYM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-K4FMZB4Y.js +0 -23
- package/dist/cli-bundle/focused-chunks/chunk-PF553UVP.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-RUCG6UWN.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-SGWYNU7T.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TGS5RXBY.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-WD43E7RU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-YM4AMP7H.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-F4SN7TXJ.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-7R2FXJ5O.js +0 -2
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{a as Z_}from"./chunk-UJMQP2HP.js";import{a as or,e as ar,g as Wi,h as ee,l as Ra,w as L_}from"./chunk-QQHMNUZT.js";import{Ba as B_,Ga as H_,Ka as Ma,i as Gm,ka as Oa,ua as La,va as z_,wa as Da,x as W_,xa as Na}from"./chunk-6T2V3UIK.js";import{a as ur,b as G_,i as Tt,k as yn,l as wn,m as vn}from"./chunk-ODMJ3HIB.js";import{A as gn,B as oe,D as zi,G as Bi,H as P_,Ha as X_,Ia as J_,Ic as rf,J as Ia,Ja as mr,K as $_,Ka as Pa,Lc as sf,M as F_,Na as Q_,U as U_,_a as pr,bb as bn,eb as kn,l as D_,lb as ef,o as N_,oa as V_,p as cr,pa as Y_,pb as tf,qb as nf,s as M_,y as dr,z as lr}from"./chunk-7RCI7AAA.js";import{a as jm}from"./chunk-AQ5UHHQS.js";import{$ as Ep,$a as sr,A as Qm,Aa as Bp,B as Zm,Ba as Hp,C as ep,Ca as Vp,D as tp,Da as Yp,E as np,Ea as Xp,F as rp,Fa as Jp,G as ip,Ga as Qp,H as sp,Ha as Zp,I as op,Ia as e_,Ib as E_,J as ap,Ja as t_,Jb as qi,K as cp,Ka as Ea,Kb as S_,L as dp,La as n_,Lb as Aa,M as lp,Ma as r_,Na as Sa,Nb as T_,O as up,Oa as i_,Ob as C_,P as ba,Pa as s_,Q as mp,Qa as o_,Qb as A_,R as pp,Ra as a_,Rb as x_,S as _p,Sa as c_,Sb as Ki,T as fp,Ta as St,Tb as R_,U as hp,Ua as d_,V as gp,Va as l_,W as yp,Wa as u_,X as wp,Xa as m_,Y as vp,Z as bp,Za as p_,Zb as xa,_ as kp,aa as Sp,ba as Tp,bb as __,bc as I_,ca as Cp,cb as f_,d as ga,da as ka,db as h_,e as qm,ea as Ap,eb as g_,ec as O_,fa as xp,ga as Rp,gb as y_,h as Km,ha as Ip,i as ya,ia as Op,j as jt,ja as Lp,ka as Dp,kb as Ta,l as Wm,la as Np,lb as w_,ma as Mp,mb as v_,na as Pp,nb as Ca,oa as $p,ob as b_,pb as k_,q as wa,r as va,s as Gi,sa as Fp,t as zm,ta as Up,u as Bm,ua as jp,v as Hm,va as Gp,w as Vm,wa as qp,x as Ym,xa as Kp,y as Xm,ya as Wp,z as Jm,za as zp}from"./chunk-5S6RT5LX.js";import{d as Pm,j as $m,r as Fm,s as Ut,t as Um}from"./chunk-T56MB6SF.js";import{A as Xn,Ab as $t,B as Jn,C as hi,Cb as hn,D as at,Db as me,E as du,F as gi,Fa as Pi,Fb as la,Gb as km,Ia as fn,Ja as cm,Ka as dm,La as pm,N as vi,Oc as ma,P as kt,Pc as pa,Q as Ei,Qb as Em,Qc as _a,R as Si,Rc as fa,S as Tu,Sa as _m,Tc as Im,Vb as Sm,Xb as Tm,Xc as ha,_a as fm,_b as ua,_c as Om,aa as Ii,ab as hm,ac as Cm,c as Oe,cc as Am,dd as Lm,e as ql,ea as Ze,ec as Ft,ed as Dm,f as ai,fa as sm,fd as Ui,g as ci,gd as Nm,h as Kl,ha as Oi,i as di,ia as om,j as Wl,ja as Li,k as Q,ka as Di,kd as ji,l as sn,la as Ni,lb as gm,ld as Mm,m as Hn,mb as ym,n as we,pa as Mi,pb as wm,pc as xm,qb as $i,r as Je,rb as vm,sa as am,t as Dt,tb as V,tc as Rm,ub as ue,v as li,va as ir,w as on,wb as Fi,x as ge,xb as Ee,y as ui,yb as lt,z as ra,zb as bm}from"./chunk-DSCFJTHB.js";import{$a as su,$d as Au,$e as tr,A as Dl,Aa as Zo,Ad as bu,Ai as rr,B as Nl,Ba as Vn,Bc as Zn,Bd as Ue,Bh as Qu,C as Ml,Ca as Se,Cd as ku,Ch as Zu,D as Pl,Dd as Eu,De as Pu,Dh as em,Di as pn,E as $l,Ed as Su,Ei as _n,F as Fl,Fa as P,Fi as da,G as Xe,Ga as st,Gb as I,Gf as zu,Gg as Vu,H as Ul,Ha as _i,Hb as uu,Hg as Yu,Ia as cn,Ib as ia,Ja as Yn,Jb as mu,Jg as Xu,Ka as Nt,Kb as wi,Ki as lm,Le as $u,Mb as le,Me as Fu,N as jl,Na as R,Ne as Uu,O as Gl,Oa as Qe,Ob as pu,Od as Cu,Oe as ju,P as Yo,Pa as qe,Pe as Gu,Qa as Te,Qe as mn,Ra as Zl,Re as qu,Sa as eu,Sb as _u,Ta as ot,Td as Ti,Th as tm,Ti as um,Ua as fi,Ub as fu,Ui as x,Va as tu,Vi as mm,Wa as nu,Wb as Qn,Wd as q,Xa as ea,Xc as bi,Xd as Ke,Ya as ta,Yb as hu,Yd as ln,Ye as Ku,Za as ru,Zc as ki,_a as iu,_d as Et,a as ne,ab as ou,ae as sa,af as nr,ag as Bu,b as $e,bb as au,be as xu,c as Ol,cb as cu,cc as gu,ce as oa,d as Ll,db as na,de as Ru,ea as Xo,eg as Hu,ej as F,fe as Iu,gb as W,gd as yu,ge as Ou,ha as Jo,he as Ci,ia as Fe,ib as dn,ie as er,ja as mi,jg as ca,ji as nm,ka as pi,ke as Ai,kf as Wu,ki as rm,la as Bl,ma as Hl,mb as lu,mi as im,na as Vl,ne as xi,oa as Yl,od as M,oe as se,of as aa,pa as Xl,pe as Mt,pf as U,ph as Ju,qa as Jl,qe as fe,ra as Ql,rb as ie,re as un,rf as dt,s as Ye,sa as Qo,se as Lu,te as Du,u as H,ub as yi,v as oi,vd as wu,ve as Ri,w as Lt,wd as vu,we as Nu,xe as Mu,zd as ct,zi as Pt}from"./chunk-3OXQGGRD.js";import{a as K_}from"./chunk-SPPHDVZE.js";import{c as j_}from"./chunk-RSAN2YUU.js";import{b as q_}from"./chunk-VS565KBX.js";import{A as m,C as p,D as bt,E as re,F as an,G as j,H as Z,K as Le,M as zl,a as Tl,m as Cl,p as Al,s as xl,u as Rl,w as Il,x as si,y as Ot}from"./chunk-O4ZLEN4T.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2e89d3c-9abc-5ca7-a290-69a54dd694ab")}catch{}})();var Vk=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),Yk=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),Xk=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),Jk=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),Qk=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),Zk=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],e0=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),t0=new Set(["--only-index"]),n0=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),r0=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),i0=new Set(["--regression"]);function s0(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:Jk.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:Yk.has(t)&&Xk.has(e)?["argv","stdin"]:["argv"]}function o0(e,t){let n=n0.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||Zk.some(i=>t.flag.startsWith(i));return n||t0.has(t.flag)||!e0.has(t.flag)&&!r}function a0(e,t){return t.value_arity!==void 0?t.value_arity:o0(e,t)?i0.has(t.flag)||r0.has(`${e}:${t.flag}`)?"optional":"required":"none"}function c0(e,t){let n=oi(e),r=a0(n,t),i=r!=="none",s=s0(n,t.flag),o=t.description??Vk[t.flag]??`${i?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:o,takes_value:i,value_required:r==="required",...i?{value_name:t.value_name??"value"}:{},value_type:i?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...Qk.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function of(e,t){return t.map(n=>c0(e,n))}function CF(e,t,n){let r=e.trim().toLowerCase(),i=[],s=new Map,o=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(o+=1,s.has(c.flag)){i.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){i.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&i.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())a.has(c.flag)||i.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return i.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:i.length===0,declared_count:t.length,observed_count:o,findings: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]="0c0bb7ab-6157-5861-ad7e-a63ae62220f4")}catch{}})();var d0=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),l0=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),u0=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),m0=new Set(["extension","install","package","packages","upgrade"]);function p0(e){let t=H(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,r]of Object.entries(u0))if(r.has(t))return n;return m0.has(t)?"extensions":"internal"}var En=Object.freeze([...Xe.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...Ye.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:d0.has(H(e))?"core":l0.has(H(e))?"standard":"full",family:p0(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),_0=En,af=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),IF=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function OF(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=af.max_lines&&n<=af.max_utf8_bytes}}var cf={core:0,standard:1,full:2,internal:3},df=new Map(_0.map(({command:e,tier:t})=>[e,t]));function $a(e,t="standard"){return df.get(e.trim().toLowerCase())??df.get(H(e.trim().toLowerCase()))??t}function LF(e){return lf(e,En)}function lf(e,t){let n=cf[e];return t.filter(r=>r.tier!=="internal"&&cf[r.tier]<=n).map(r=>r.command)}function DF(e){return uf(e,En)}function uf(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var f0=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],h0=new Set([...Lt.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function NF(e=En){return f0.map(t=>({family:t,commands:uf(t,e).filter(n=>e.find(r=>r.command===n)?.tier!=="internal"&&!h0.has(n))})).filter(({commands:t})=>t.length>0)}var g0=Object.freeze({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_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function MF(e,t){return y0(e,t,En)}function y0(e,t,n){if(t==="full")return[...e];let r=new Set(lf(t,n));return e.filter(i=>{let s=g0[i];return s!==void 0&&r.has(s)})}var PF=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),$F=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function FF(){return w0(En)}function w0(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:t,tier:n,family:r})=>`| \`${t}\` | ${n} | ${r} |`),""].join(`
|
|
2
|
+
`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7df4fe91-e8a4-540f-8737-c67f2efa460e")}catch{}})();var Fa=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],v0=new Map(Fa.map(e=>[e.exit_code,e.class]));function Hi(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function b0(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let i=r.state.trim(),s=r.probe_id.trim(),o=Hi(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(i)||!/^[a-z][a-z0-9-]*$/.test(s)||o.length===0||t.has(i)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(i),n.add(s),{state:i,probe_id:s,entrypoints:o,expected_exit_class:r.expected_exit_class}}).sort((r,i)=>r.state.localeCompare(i.state))}function k0(e,t,n,r,i){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(r),i.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),v0.get(e.exit_code)===e.class].includes(!1)}function E0(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let i=t.get(n.canonical_code);if(!i)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=i}return n}function S0(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=E0(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let i=e.filter(s=>s.code!==r.code&&s.canonical_code===r.code).map(s=>s.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(i):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function pf(e){let t=new Set,n=e.map(r=>{let i=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let s=Hi(r.sources),o=Hi(r.emitting_commands),a=(r.canonical_code??i).trim(),c=Hi(r.aliases??[]),d=b0(r.owned_states);if(!k0(r,s,o,a,c))throw new TypeError(`Invalid pm error code contract: ${i}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${i}`);return Object.freeze({...r,code:i,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:s,emitting_commands:o,canonical_code:a,aliases:c,owned_states:d})});return S0(n),Object.freeze(n.sort((r,i)=>r.code.localeCompare(i.code)))}function jF(e,t){let n=mf(e,t);return mf(n.canonical_code??n.code,t)}function mf(e,t){let n=e.trim(),r=t.find(i=>i.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e8c03e6-149a-5819-a000-65e7e3b12f6d")}catch{}})();var T0="Inspect the structured error guidance and retry the suggested command.",C0=new Map(Fa.map(e=>[e.exit_code,e.class]));function _f(e){return e.map(t=>{let n=`${t.code.replaceAll("_"," ")} condition.`,r={code:t.code,meaning:`${n.charAt(0).toUpperCase()}${n.slice(1)}`,stability:t.stable?"stable":"provisional",exit_code:t.exit_code,class:C0.get(t.exit_code),recovery:T0,sources:t.sources,emitting_commands:t.emitting_commands??["*"],canonical_code:t.canonical_code??t.code,aliases:t.aliases??[]};return t.owned_states&&(r.owned_states=t.owned_states),r})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ba993890-a230-521a-aac4-d873cbd184ba")}catch{}})();var ff=[{code:"acceptance_criteria_mutation_conflict",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_remove_unmatched",exit_code:3,sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_semicolon_forbidden",exit_code:2,stable:!0,sources:["core/item/parse.ts"]},{code:"accepted_rejected_value",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"alias_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"alias_target_missing",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"already_claimed_by",exit_code:4,stable:!0,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_option_combination",exit_code:2,stable:!0,sources:["sdk/lifecycle/claim.ts","sdk/lifecycle/plan.ts"],emitting_commands:["claim","plan"]},{code:"annotation_alias_conflict",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"annotation_flag_like_value",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_if_absent_without_append",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_message_without_text",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_transposed_subcommand",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"append_empty_body",exit_code:2,stable:!0,sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"assurance_registry_invalid",exit_code:1,sources:["sdk/governance/assurance.ts"]},{code:"bare_comma_entry_ambiguous",exit_code:2,sources:["core/item/parse.ts"]},{code:"blocker_identity_read_failed",exit_code:1,sources:["sdk/query/declared-blockers.ts"]},{code:"body_file_conflicts_with_body",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_missing_path",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_unreadable",exit_code:3,stable:!0,sources:["core/io/body-file.ts"]},{code:"budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"bulk_create_route",exit_code:2,sources:["cli/register-mutation.ts"]},{code:"bulk_ids_input_empty",exit_code:2,sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",exit_code:2,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",exit_code:3,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",exit_code:1,stable:!0,sources:["cli/bundle-integrity.ts"]},{code:"capability_undeclared",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"capability_unused",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"child_projection_item_bound_exceeded",exit_code:1,stable:!0,sources:["sdk/item-children.ts"]},{code:"close_reason_required",exit_code:2,stable:!0,sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",exit_code:1,stable:!0,sources:["core/telemetry/observability.ts"]},{code:"close_validation_missing_fields",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"collection_transposed_subcommand",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"command_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"command_namespace",exit_code:2,stable:!0,sources:["sdk/cli-contracts/runtime-contracts.ts"]},{code:"command_override_conflict",exit_code:4,stable:!0,sources:["sdk/compose.ts"]},{code:"config_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"config_key_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"config_value_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"conflicting_lifecycle_owner",exit_code:2,stable:!0,sources:["cli/register-operations.ts"]},{code:"context_evaluation_read_incomplete",exit_code:2,sources:["sdk/context-relevance.ts"]},{code:"context_signal_store_invalid",exit_code:2,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_stale",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_write_failed",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_takes_no_item_argument",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"core_item_field_requires_dedicated_flag",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"create_positional_type_without_title",exit_code:2,stable:!0,sources:["cli/register-mutation.ts"]},{code:"dependency_cardinality_created",exit_code:2,sources:["sdk/graph/cardinality-integrity.ts"]},{code:"dependency_edge_not_allowed",exit_code:2,stable:!0,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_flag_value_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_remove_no_match",exit_code:3,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"dependency_target_not_found",exit_code:3,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_temporal_order_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"duplicate_canonical_flag",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"duplicate_command",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"duplicate_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"duplicate_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"duplicate_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"duplicate_probe",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"duplicate_sweep_cost_limit",exit_code:4,stable:!0,sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"]},{code:"duplicate_target_circular",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_corpus",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"empty_surface",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"event_cursor_query_mismatch",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"event_history_integrity_failed",exit_code:1,sources:["core/history/event-index.ts"]},{code:"event_index_unavailable",exit_code:1,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"exit_code_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"expect_hash_background_unsupported",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invalid",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invocation_rewritten",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_requires_mutation",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_target_required",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expected_revision_duplicate",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"expected_revision_scope_conflict",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"extension_command_activation_failed",exit_code:1,stable:!0,sources:["cli/commander-usage.ts"]},{code:"extension_dependency_name_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_spec_invalid",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_version_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_flag_value_invalid",exit_code:2,sources:["cli/extension-command-options.ts"]},{code:"extension_install_incomplete_source_scan",exit_code:2,sources:["sdk/extension/install-plan.ts"]},{code:"extension_install_rollback_failed",exit_code:1,sources:["sdk/extension/install-snapshot.ts"]},{code:"extension_install_soft_failed",exit_code:1,stable:!0,sources:["cli/register-setup.ts"]},{code:"extension_install_source_contains_destination",exit_code:2,stable:!0,sources:["sdk/extension/install-runtime.ts"]},{code:"extension_item_field_reserved",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_type_conflict",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_unknown",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_mutation_guard_failed",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_decision",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_denial",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_timed_out",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_read_output_invalid",exit_code:2,sources:["sdk/read-output/extension.ts"]},{code:"extension_update_health_partial_coverage",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"extensions_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"field_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_mcp_input_collision",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"github_source_entry_unbuilt",exit_code:2,stable:!0,sources:["sdk/extension/shared.ts"]},{code:"hierarchy_cardinality_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_cycle_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_parent_divergence_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"history_author_acknowledge_plan_conflict",exit_code:4,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_plan_fingerprint_required",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_preview_limit_invalid",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_required_values_missing",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_conflict",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_required",exit_code:2,stable:!0,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_not_actionable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_unreadable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_baseline_unavailable",exit_code:1,sources:["core/history/projection.ts"]},{code:"history_drift_chain_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_missing_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/history/read.ts"],canonical_code:"merge_conflict_markers_detected"},{code:"history_replay_invalid",exit_code:1,sources:["core/history/projection.ts","core/history/tombstone.ts"]},{code:"history_salvage_refused",exit_code:4,sources:["sdk/history/salvage.ts"]},{code:"history_stream_over_compact_threshold",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"history_target_out_of_range",exit_code:1,stable:!0,sources:["core/history/projection.ts"]},{code:"history_timestamp_invalid",exit_code:1,sources:["core/history/event-index.ts","core/history/history.ts"]},{code:"history_union_rebase_conflict",exit_code:4,sources:["sdk/merge/history-scalar-rebase.ts"]},{code:"history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",exit_code:2,sources:["core/history/version-address.ts"]},{code:"history_version_pruned",exit_code:2,sources:["core/history/projection.ts"]},{code:"host_environment_capacity_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_operation_invalid",exit_code:2,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_permission_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_resource_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"improvement_metric_contract_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"improvement_observation_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"incomplete_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"inconsistent_concept_kind",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"init_existing_settings_requires_force",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_gitignore_unwritable",exit_code:1,stable:!0,sources:["sdk/workspace.ts"]},{code:"init_id_prefix_conflict",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_id_prefix_path_like",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"integrity_history_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_history_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_ahead_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_outdated_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"invalid_argument_value",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/item/priority.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/dependencies.ts","sdk/governance/assurance-mutation-error.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts","sdk/query/next.ts","sdk/runtime-input.ts","sdk/runtime/mutation-admission.ts","sdk/runtime/mutation-value-validation.ts","sdk/runtime/schema-preview.ts","sdk/workspace.ts"],emitting_commands:["*","create","next","task-composition","update","update-many"]},{code:"invalid_command_usage",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"invalid_event_cursor",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_cursor_mode",exit_code:2,sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"]},{code:"invalid_event_follow_interval",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_limit",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_since",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_history_analytics_limit",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_minimum_sample",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_since",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_improvement_ledger",exit_code:1,sources:["sdk/improvement-ledger-validation.ts"]},{code:"invalid_improvement_metric",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_limit",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_timestamp",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_provenance_predicate",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"invalid_query_cursor",exit_code:2,stable:!0,sources:["sdk/pagination.ts","sdk/query/window-pagination.ts"]},{code:"invalid_read_output_session",exit_code:2,sources:["sdk/read-output-session.ts"]},{code:"invalid_reproducible_process_environment",exit_code:2,sources:["sdk/reproducibility/process.ts"]},{code:"invalid_workspace_snapshot_target",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"item_already_active",exit_code:4,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"item_already_exists",exit_code:4,stable:!0,sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"]},{code:"item_deleted",exit_code:3,sources:["core/history/tombstone.ts"]},{code:"item_document_encoding_invalid",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_document_invalid",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_document_roundtrip_failed",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_format_version_unsupported",exit_code:4,sources:["core/item/item-format.ts"]},{code:"item_id_collision",exit_code:4,stable:!0,sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_identity_ambiguous",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_identity_conflict",exit_code:4,sources:["sdk/governance/validate-history-drift.ts","sdk/lifecycle/item-revision.ts","sdk/merge/three-way.ts","sdk/query/declared-blockers.ts"]},{code:"item_identity_reserved",exit_code:4,sources:["core/history/history.ts"]},{code:"item_not_found",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/item-store.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"]},{code:"item_revision_conflict",exit_code:4,sources:["core/store/item-mutation-precondition.ts"]},{code:"likely_duplicate",exit_code:4,stable:!0,sources:["sdk/similarity.ts"]},{code:"linked_artifact_mutation_conflict",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_resource_positional_value",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_test_command_immutable",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_command_not_executable",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_context_invalid",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_patch_fields_unsupported",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_remove_no_match",exit_code:3,sources:["sdk/test/execution.ts"]},{code:"linked_test_update_ambiguous",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_update_no_match",exit_code:3,sources:["sdk/test/update.ts"]},{code:"linked_test_value_not_quoted",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"list_source_incomplete",exit_code:1,stable:!0,sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"local_source_not_found_bare_name",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"lock_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"]},{code:"lock_lost",exit_code:4,sources:["core/lock/lock.ts"]},{code:"lock_path_unsafe",exit_code:4,sources:["core/lock/lock-confinement.ts"]},{code:"locks_stale_count",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"locks_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"malformed_plan_step_evidence",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"managed_state_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"managed_state_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_capabilities_absent",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"manifest_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_unknown_key",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"mcp_annotation_file_unavailable",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"mcp_stdin_unavailable",exit_code:2,sources:["sdk/annotations.ts"]},{code:"mcp_task_not_found_or_not_authorized",exit_code:3,sources:["sdk/mcp/tasks.ts"]},{code:"merge_artifacts_ignored",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_bun_launcher_unavailable",exit_code:5,sources:["sdk/merge/install.ts"]},{code:"merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/item/item-format.ts"],aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_git_config_unwritable",exit_code:5,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_receipt_evidence_invalid",exit_code:4,sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"]},{code:"merge_receipt_history_reference_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_receipt_not_portable",exit_code:4,sources:["sdk/merge/receipts.ts"]},{code:"merge_receipts_pending",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_reconcile_receipt_evidence_untrusted",exit_code:4,sources:["sdk/history-repair.ts"]},{code:"merge_root_not_found",exit_code:3,stable:!0,sources:["sdk/merge/install.ts"]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a831620-2973-5048-b691-f90e85f99dc2")}catch{}})();var hf=[{code:"merge_settlement_hook_conflict",exit_code:4,sources:["sdk/merge/settlement-hook.ts"]},{code:"merge_settlement_review_required",exit_code:4,sources:["sdk/merge/ignored-artifacts.ts","sdk/merge/reconcile.ts","sdk/merge/stage.ts"]},{code:"missing_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"missing_cli_flag",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_directory",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"missing_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_lifecycle_target",exit_code:2,stable:!0,sources:["sdk/extension.ts"]},{code:"missing_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"missing_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_parameter_alias",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_positive_execution_receipt",exit_code:1,sources:["sdk/test/execution.ts"]},{code:"missing_probe",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_required_argument",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts","sdk/lifecycle/claim.ts"],emitting_commands:["*","claim"]},{code:"missing_required_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"missing_suggested_retry",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_suggested_retry_args",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"module_import_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"multi_target_github_install_ambiguous",exit_code:2,stable:!0,sources:["cli/register-setup.ts"]},{code:"mutation_author_required",exit_code:2,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"mutation_document_unreadable",exit_code:2,sources:["cli/register-structured-mutation.ts"]},{code:"mutation_option_value_invalid",exit_code:2,sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"]},{code:"mutation_secret_guard_blocked",exit_code:4,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"no_matching_tests",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_projects_matched_filters",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_test_files_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_tests_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_update_fields",exit_code:1,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"no_version_bounds_declared",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"npm_pack_json_shape_unsupported",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_missing",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_unsafe",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_not_found",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"ownership_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"]},{code:"ownership_dependency_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"package_upgrade_modes_mutually_exclusive",exit_code:2,sources:["sdk/governance/upgrade.ts"]},{code:"positional_shape_budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"positional_signature_mismatch",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"profile_name_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_name_not_normalized",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_summary_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_title_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"project_runtime_history_epoch_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_item_format_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_mutation",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_read",exit_code:1,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_schema_field_requires_declared_flag",exit_code:2,sources:["core/extensions/item-fields.ts"]},{code:"projection_options_mutually_exclusive",exit_code:2,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"provenance_value_domain_invalid",exit_code:2,sources:["core/diagnostics/remediation.ts"]},{code:"read_output_cursor_command_mismatch",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_invalid",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_stale",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"recovery_kind_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"redundant_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"refusal_allowed_values_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_exit_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_mutated_state",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_probe_missing",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_recovery_failed",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"reindex_already_running",exit_code:4,stable:!0,sources:["sdk/governance/reindex.ts"]},{code:"removed_canonical_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"removed_compatibility_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"reopen_reason_required",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reopen_receipt_missing",exit_code:1,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"reopen_target_status_invalid",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reported_zero_passes",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reported_zero_tests",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reserved_item_field",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"retry_failed",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"schema_migration_input_required",exit_code:2,stable:!0,sources:["cli/migration-gates.ts"]},{code:"semantic_spelling_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"settings_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_read_fs_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_schema",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_merge_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_section_document_malformed",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_document_missing",exit_code:3,sources:["core/store/settings-sections.ts"]},{code:"settings_section_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_name_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_reserved",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_revision_conflict",exit_code:4,sources:["core/store/settings-sections.ts"]},{code:"settings_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_write_assigned_path_invalid",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_json",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_schema",exit_code:2,sources:["core/store/settings.ts"]},{code:"stale_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"stale_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_revision",exit_code:4,sources:["core/store/item-store.ts"]},{code:"start_blocked_by_open_dependency",exit_code:4,sources:["sdk/lifecycle/start-blockers.ts"],emitting_commands:["claim","start-task","update"]},{code:"status_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_lifecycle_role_required",exit_code:2,sources:["sdk/schema.ts"]},{code:"stdin_json_invalid",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"stdin_json_persisted_annotation_changed",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"stdin_json_unknown_key",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"structured_event_immutable",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"structured_event_input_conflict",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_empty",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_since_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"suggested_retry_args_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"telemetry_endpoint_probe_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_endpoint_probe_http_status",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_otel_export_failing",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_high_retries",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_invalid_rows",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_pending",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_schema_version_behind",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_state_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"template_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"terminal_plan_mutation",exit_code:4,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",exit_code:4,stable:!0,sources:["core/telemetry/observability.ts","sdk/lifecycle/claim.ts"],emitting_commands:["*","claim"]},{code:"test_measure_requires_execution",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"test_measure_requires_run",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"text_unpaired_surrogate",exit_code:2,sources:["core/item/item-format.ts","core/shared/output-unicode.ts"]},{code:"tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",exit_code:3,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",exit_code:2,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",exit_code:1,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_abandoned",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_committed",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_create_compensated",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_journal_invalid",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_partial_mutation",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_plan_mismatch",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_preview_external_schema",exit_code:2,sources:["sdk/item-transaction.ts"]},{code:"transaction_preview_non_regular_file",exit_code:2,sources:["core/fs/fs-utils.ts"]},{code:"transaction_preview_snapshot_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_recovery_plan_missing",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"type_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"type_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"undeclared_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"unexpected_refusal_probe",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"unknown_command",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"]},{code:"unknown_context_intent",exit_code:2,stable:!0,sources:["sdk/context-intent-contracts.ts"]},{code:"unknown_error",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"unknown_field",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_field_projection",exit_code:2,stable:!0,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"unknown_item_type",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_lifecycle_action",exit_code:2,stable:!0,sources:["sdk/agent/subcommand-recovery.ts"],canonical_code:"unknown_subcommand"},{code:"unknown_noun",exit_code:2,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"unknown_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts"],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"unknown_status",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_subcommand",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"unsupported_update_option",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"upsert_key_ambiguous",exit_code:4,sources:["sdk/structured-mutations.ts"]},{code:"upsert_key_conflict",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"upsert_key_duplicate",exit_code:2,sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"]},{code:"upsert_key_missing",exit_code:2,sources:["sdk/structured-mutations.ts"]},{code:"upsert_match_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"validate_command_references_stale_pm_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_missing_linked_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_orphaned_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_format_version_ahead_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_ahead_format_version"},{code:"validate_format_version_outdated_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_outdated_format_version"},{code:"validate_hierarchy_parent_cycle",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_hierarchy_parent_cycle_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_history_drift_chain_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_chain_mismatch"},{code:"validate_history_drift_hash_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_hash_mismatch"},{code:"validate_history_drift_missing_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_missing_stream"},{code:"validate_history_drift_unreadable_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_unreadable_stream"},{code:"validate_history_drift_version_skews",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_version_skew"},{code:"validate_history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_unknown_author_events"},{code:"validate_lifecycle_active_closure_like_metadata",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_active_terminal_parent",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_stale_blockers",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_driver_configuration",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_fence_drift",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_custom_profile_missing_required_fields",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_duplicate_issue_codes",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_acceptance_criteria",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_close_reason",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_closed_at",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_confidence",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_estimate",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_release",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_reviewer",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_risk",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_sprint",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_resolution_missing_fields",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_duplicate_item_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_history_conflict_markers",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_history_conflict_marker"},{code:"validate_storage_resurrected_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"tracked_runtime_cache_files"},{code:"validate_storage_unparseable_config",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unparseable_history",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unreadable_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_embedding_identity_changed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_stale_items_remaining",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"visible_surface_ceiling_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"workflow_duplicate_type",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_policy_approval_history_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_audit_failed",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_input_unreadable",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_invalid",exit_code:2,sources:["core/policy/workflow-policy.ts"]},{code:"workflow_policy_refused",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_registry_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_status_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_transition_malformed",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workspace_history_chain_invalid",exit_code:4,sources:["core/history/workspace-history.ts"]},{code:"workspace_history_state_conflict",exit_code:4,stable:!0,sources:["core/history/workspace-history.ts"]},{code:"workspace_root_pm_path",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"workspace_snapshot_force_required",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_manifest_mismatch",exit_code:4,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_name_reserved_fingerprint",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_not_found",exit_code:3,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_permission_denied",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_resource_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_storage_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"wrong_item_type",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b525d8c8-3a70-52bd-83db-c956aba0c6fb")}catch{}})();var gf=pf(_f([...ff,...hf]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="76c420db-b520-5fde-bd43-16a7324feb0a")}catch{}})();var A0=["mutation_receipt","entity","collection","diagnostic","stream"],x0=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),R0=new Set(["close-many","update-many"]),I0=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),O0=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function _r(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!A0.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function yf(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return R0.has(n)?_r({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):x0.has(n)?_r({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):I0.has(n)?_r({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):O0.has(n)?_r({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):_r({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var L0=Xe.map(e=>yf(e)),D0=new Map(L0.map(e=>[e.command,e]));function wf(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=oi(t).split(" "),r=D0.get(n);return r?{...r,command:t}:yf(t)}function N0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M0(e){return N0(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function ZF(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!M0(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.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]="7c95b311-b408-50f7-87e8-2c2fa2323092")}catch{}})();var Ua=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],vf=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],P0=new Set(["close-many","update-many"]),kf=Xe.map(e=>({command:e,exit_codes:P0.has(e)?[...vf,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...vf]})),bf=new Map(kf.map(e=>[e.command,e])),$0=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function r1(e){return $0.includes(e)}function i1(e){return Ua.some(t=>t.exit_code===e)}function Ef(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return bf.get(t)??bf.get(t.split(" ")[0])}function s1(e,t=Xe,n=kf){let r=new Map(n.map(c=>[c.command,c])),i=t.filter(c=>!r.has(c)),s=e.filter(c=>{let d=r.get(c.command)??r.get(c.command.split(" ")[0]);return d===void 0||!d.exit_codes.includes(c.exit_code)}),o=new Set(e.map(c=>c.exit_code)),a=[...new Set(n.flatMap(c=>c.exit_codes))].filter(c=>!o.has(c)).sort((c,d)=>c-d);return{ok:i.length===0&&s.length===0&&a.length===0,missing_commands:i,undeclared_observations:s,unreachable_exit_codes:a}}function o1(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var D=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Ce=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},et=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function Sn(e){try{return await e()}catch(t){throw t instanceof D?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function ja(e){try{return await e()}catch(t){throw t instanceof Ce?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as F0}from"node:crypto";import U0 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]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var Tn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var Tf=1,ut=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],fr=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],j0=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],G0=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Vi=30,Yi=5e3,Cf=4,q0=50;function mt(e,t){if(!G0.test(e))throw new D(`${t} must be a stable lowercase id`)}function K0(e,t){if(!Number.isFinite(e)||e<0)throw new D(`${t} must be a finite non-negative number`)}function hr(e){let t=j0.filter(i=>e[i]!==void 0);if(t.length!==1)throw new D(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function qa(e,t){return ne(e)===ne(t)}function Af(e,t){if(t.polarity==="equals")return qa(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function xf(e){let t=hr(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>Af(r.observed,t)===(r.expected==="pass"))}function W0(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!qa(e.value,t.value)}function z0(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||ne(e.scope)!==ne(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return W0(hr(e),hr(t))||n[t.enforcement]<n[e.enforcement]||r}function B0(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new D("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new D("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new D("items source equals/state requires field")}function H0(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new D("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new D("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new D("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new D("dependency_kind source source_kind_state must be present or missing")}function V0(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new D("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new D("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new D("prose_edge_gap exemption selectors must not be empty")}}function Ka(e){mt(e.id,"measurement.id"),e.max_cost!==void 0&&K0(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new D(`measurement.source.kind must be one of ${fr.join(", ")}`);let n=Reflect.get(t,"kind");if(!fr.includes(n))throw new D(`measurement.source.kind must be one of ${fr.join(", ")}`);let r=t;if(r.kind==="items"&&B0(r),r.kind==="dependency_kind"&&H0(r),r.kind==="prose_edge_gap"&&V0(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new D(`${r.kind} source requires field`);return r.kind==="provider"&&(mt(r.provider,"provider source provider"),mt(r.key,"provider source key")),e}function Wa(e){if(mt(e.id,"assertion.id"),mt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new D("assertion.owner_item_id is required");let t=hr(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new D(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new D("retired assertion requires retire_reason");e.scope.kind==="filter"&&mt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new D("assertion negative control requires pass and fail cases");if(!xf(e))throw new D(`assertion ${e.id} negative control does not prove its bound`);return e}function Y0(e){if(!Array.isArray(e.allowed_providers))throw new D("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)mt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new D("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!ut.includes(t))throw new D(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new D(`gate provider policy trigger ${t} is invalid`)}}function Rf(e){if(mt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new D("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new D("gate requires at least one assertion");for(let t of e.assertion_ids)mt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new D(`gate.triggers is required and must be an array of ${ut.join(", ")}`);if(e.triggers.length===0)throw new D("gate requires at least one trigger");for(let t of e.triggers)if(!ut.includes(t))throw new D(`gate trigger must be one of ${ut.join(", ")}`);return e.provider_policy&&Y0(e.provider_policy),e}function Cn(e){if(e.version!==Tf)throw new D(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Ka(r),t.has(`measurement:${r.id}`))throw new D(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Wa(r),t.has(`assertion:${r.id}`))throw new D(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){Rf(r);let i=r.assertion_ids.filter(s=>!e.assertions.some(o=>o.id===s));if(i.length>0)throw new D(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new D(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of If(e))if(!n.has(r))throw new D(`${i.join(", ")} references missing measurement ${r}`);return e}function za(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)za(n,t)}function If(e){let t=new Map,n=(r,i)=>{let s=t.get(r)??[];s.push(i),t.set(r,s)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];za(r.source.expression,i);for(let s of i)n(s,`derived measurement ${r.id}`)}return t}function X0(e,t){let n=e.assertion_ids.flatMap(s=>{let o=t.assertions.find(a=>a.id===s);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let s=n.pop();if(r.has(s))continue;r.add(s);let o=t.measurements.find(a=>a.id===s);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&za(o.source.expression,n)}return i}function gr(){return{version:Tf,measurements:[],assertions:[],gates:[]}}function J0(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let s=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?s:!s}return qa(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Q0(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function Z0(e,t){let n=[],r=Qn(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let s of i.dependencies??[]){let o=Qn(s.kind)??s.kind.trim().toLowerCase(),a=s.source_kind?.trim();o===r&&Q0(e,a)&&n.push(`${i.id}->${s.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function eE(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let s=Reflect.get(i,"text");typeof s=="string"&&t.push(s)}}}return t}function tE(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function Ga(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function nE(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,s=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let a of o.dependencies??[])n.add(Ga(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(Ga(o.id,a));for(let a of eE(o)){let c=[...a.matchAll(i)].map(d=>d[0]);s+=c.length,r.push({holder_id:o.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:s}}function rE(e,t){let n=nE(t.items),r=new Map;for(let o of n.prose_mentions){let a=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(a)];for(let d of c){let l=Ga(o.holder_id,d);if(n.linked_pairs.has(l)||tE(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(_=>_!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],s=i.map(o=>o.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function iE(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function sE(e,t){let n=t.items.filter(r=>{let i=r[e.link],s=Array.isArray(i)&&i.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function oE(e,t){let n=e.source;return n.kind==="items"?J0(n,t):n.kind==="dependency_kind"?Z0(n,t):n.kind==="prose_edge_gap"?rE(n,t):n.kind==="history"?iE(n,t):n.kind==="links"?sE(n,t):null}function Of(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function aE(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Lf(e,t,n){let r=new Array(e.length),i=0,s=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(s),r}async function Df(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await Nf(o,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[a.cost];return i.charged.add(o.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let s=await Lf(e.operands,Cf,o=>Df(o,t,n,r,i));return{value:aE(e.operator,s.map(o=>o.value)),costs:s.flatMap(o=>o.costs),population_size:Math.max(0,...s.map(o=>o.population_size)),contributors:[...new Set(s.flatMap(o=>o.contributors))]}}async function cE(e,t,n,r,i){Ka(e);let s=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await Df(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=oE(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-s},l=Of([...a,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Ce(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${F0("sha256").update(ne(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Nf(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let s=i.cache.get(e.id);if(s)return s;let o=cE(e,t,n,r,i).catch(a=>{if(a instanceof et&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new et(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,o),o}async function Ba(e,t,n=[e]){return Nf(e,t,n,[],{cache:new Map,charged:new Set})}function dE(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function lE(e,t,n={}){Wa(e);let r=hr(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:dE(t.value,r),verdict:i?"retired":Af(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:xf(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function uE(e,t,n,r){let i=X0(e,t);if(i.size===0)return;let s=e.provider_policy,o=s?.triggers[r];if(!s||!o)throw new Ce(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!a.has(d))throw new Ce(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Ce(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new Ce(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new Ce(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function Sf(e,t,n,r,i){try{return await Ba(n,r,i)}catch(s){if(s instanceof et){let o=s.check?` check ${s.check}`:"",a=s.measurement_id??n.id,c=new Ce(`assurance gate ${e} assertion ${t} measurement ${a} source ${s.source_kind}${o} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function Mf(e,t,n,r){Cn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Ce(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Ce(`assurance gate ${e} does not declare trigger ${r.trigger}`);uE(i,t,n,r.trigger);let s=await Lf(i.assertion_ids,Cf,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!f.has(g.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,g=t.measurements.find(b=>b.id===f),y=await Sf(i.id,d.id,g,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(b=>w.has(b.id))}}let _=n.items.find(f=>f.id===d.owner_item_id),h=_!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(_.status);return lE(d,await Sf(i.id,d.id,l,u,t.measurements),{owner_terminal:h})}),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=s.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":a?"warn":"pass",exit_code:o?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Of(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Xi(e){return U0.join(e,"assurance.json")}async function Pf(e){let t=await Z(Xi(e));return t===null?gr():Ji(t)}function Ji(e){try{return Cn(JSON.parse(e))}catch(t){throw new p("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Qi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function mE(e,t){e==="measurement"?Ka(t):e==="assertion"?Wa(t):Rf(t)}async function yr(e,t){let n=structuredClone(Qi(await Pf(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function $f(e,t,n){let r=Qi(await Pf(e),t).find(i=>i.id===n);if(!r)throw new Ce(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Zi(e,t,n,r={}){mE(t,n);let i=await x(e),s=U(r.author,i.author_default),o=await _n({pmRoot:e,filePath:Xi(e),op:`assurance:${t}:put`,author:s,message:r.message,lockTtlSeconds:Vi,lockWaitMs:Yi,mutate:a=>{let c=a===null?gr():Ji(a),d=Qi(c,t),l=d.findIndex(_=>_.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&z0(d[l],n)){let _=n.authorization_decision;if(!_||!r.authorized_decision_ids?.includes(_))throw new D(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Cn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
+
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function Ha(e,t,n={}){let r=gr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),Cn(r);let i=await x(e),s=U(n.author,i.author_default),o=await _n({pmRoot:e,filePath:Xi(e),op:"assurance:bundle:apply",author:s,message:n.message,lockTtlSeconds:Vi,lockWaitMs:Yi,mutate:a=>{let c=a===null?gr():Ji(a),d=[],l=[],u=(_,h,f)=>{for(let g of h){let y=_.find(w=>w.id===g.id);if(!y){_.push(structuredClone(g)),d.push(`${f}:${g.id}`);continue}if(ne(y)!==ne(g))throw new D(`assurance bundle refuses to replace divergent ${f} ${g.id}`);l.push(`${f}:${g.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),Cn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
+
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Ff(e,t,n,r={}){let i=await x(e),s=U(r.author,i.author_default),o=await _n({pmRoot:e,filePath:Xi(e),op:`assurance:${t}:remove`,author:s,message:r.message,lockTtlSeconds:Vi,lockWaitMs:Yi,mutate:a=>{let c=a===null?gr():Ji(a);if(t==="measurement"){let u=If(c).get(n);if(u&&u.length>0)throw new D(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new D(`assurance assertion ${n} is referenced by gate`);let d=Qi(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new D(`assurance ${t} ${n} not found`);return d.splice(l,1),Cn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
5
|
+
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function Uf(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await x(e);await pn({pmRoot:e,op:"assurance:gate:verdict",author:U(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Vi,lockWaitMs:Yi})}async function jf(e,t={}){let n=t.limit??q0;if(!Number.isInteger(n)||n<1||n>Tn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${Tn}`);return(await dt(rr(e),Pt)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,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]="cf9867e5-2739-5bb0-b2f0-c432199942b6")}catch{}})();var pE=xa("list").properties.outputSession,_E={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:{...pE},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Gf={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."}},qf={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},pe={type:"string",description:"pm item id, for example pm-abc1."},fE=`Operation name (one of): ${Yo.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,hE={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."}},gE={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 K(e,t=[]){return{...qf,properties:{...qf.properties,...e},required:t}}var yE=[{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:K({action:{type:"string",enum:[...Yo],description:fE},id:pe,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."},..._E},["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:K({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:K({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:K({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:K({query:{type:"string"},options:{type:"object"},...gE},["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:K({options:{type:"object"},...hE})},{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:K({id:pe,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:K({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},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:K({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, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:K({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:pe,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"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},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"}},["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:K({id:pe,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:K({id:pe,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:K({id:pe,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:K({id:pe,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:K({id:pe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:K({id:pe,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:K({id:pe,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:K({id:pe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:K({id:pe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:K({id:pe,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:K({id:pe,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:K({id:pe,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:K({id:pe,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:K({subcommand:{type:"string",enum:[...Ul]},id:pe,target:pe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:K({id:pe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:K({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:K({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:K({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:K({...Gf,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",...Ll],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:[...Xo]},description:`Lifecycle roles for add-status: ${Xo.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:Gf}},["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:K({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:K({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:K({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."}})}],wE={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"},vE=yE.map(e=>{let t=wE[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:xa(t,{properties:n,required:r})}});function Kf(){return vE.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,i)=>r.localeCompare(i)):[];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]="bcdd81cd-9922-5292-b762-0e19da0e408c")}catch{}})();var Wf=new Map([["activity",["--limit","--after","--full"]],["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"]]]),bE=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],eh=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ts=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"]),Gt=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"]),th=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"]]),nh=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"]]),rh=new Map([...nh.entries()].flatMap(([e,t])=>pt(t).map(n=>[n,e]))),ih=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Xa=new Map(ih.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),kE=10,EE=20,zf=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."]]),sh=[["init",up],["install",pp],["uninstall",_p],["explore",fp],["manage",bp],["describe",hp],["reload",kp],["doctor",Ep],["catalog",Sp],["adopt",Tp],["adopt-all",gp],["activate",yp],["deactivate",wp],["migrate",vp]],SE=[...sh.map(([e,t])=>e==="init"?[e,mp]:[e,t]),["upgrade",ka]],TE=[...sh.map(([e,t])=>[`extension ${e}`,t]),...SE.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",cp],["config",dp],["extension",lp],["package",ba],["packages",ba],["install",Cp],["create",Vp],["item mutate",Yp],["item complete",Xp],["item reopen",Jp],["copy",Qp],["focus",Zp],["update",e_],["update-many",t_],["upgrade",ka],["calendar",Ea],["cal",Ea],["context",Sa],["ctx",Sa],["get",i_],["search",l_],["eval",c_],["events",r_],["workspace",St],["workspace position",[]],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["next",d_],["aggregate",Bm],["deps",o_],["graph",a_],["guide",s_],["reindex",Ap],["history",Qm],["history-compact",rp],["history-attest",ip],["history-redact",ep],["history-repair",tp],["history-author-acknowledge",np],["merge",Zm],["schema",sp],["profile",op],["plan",ap],["restore",Lp],["delete",Dp],["close",xp],["close-many",Rp],["append",Ip],["claim",Op],["release",Np],["start-task",Mp],["pause-task",Pp],["close-task",$p],["comments",Hm],["notes",Vm],["learnings",Ym],["files",Xm],["docs",Jm],["test",Fp],["test-runs-worker",[]],["test-all",Up],["telemetry",jp],["test-runs",Gp],["gc",qp],["stats",Kp],["ops",[]],["duplicates",Wp],["validate",Bp],["health",zp],["assurance",Hp],...p_,["contracts",u_],["completion",m_],["activity",n_],...[...eh].map(e=>[e,zm])],wr=new Map(TE);for(let{alias:e,canonical:t}of Ye){let n=wr.get(e);n!==void 0&&wr.set(t,n)}function CE(e){return rh.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Bf(e){let t=Ye.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Xe.includes(e)?ve(e):e.startsWith("extension-")?ve(`extension ${e.slice(10)}`):e.startsWith("package-")?ve(`package ${e.slice(8)}`):e.startsWith("item-")?ve(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ve(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ve(`templates ${e.slice(10)}`):ts.has(e)?nh.get(e)??ve(e):null}function AE(e,t){let n=H(t);return n!==t||Ye.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:pt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function pt(e){return e.split("|").map(t=>ve(t)).filter(t=>t.length>0)}function xE(e,t){let n=new Set(t),r=new Set;for(let i of e)if(i.command_path)for(let s of pt(i.command_path)){let o=s.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((i,s)=>i.localeCompare(s))}function es(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function vr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function RE(e,t){if(!t)return{...e};let n=vr(e).filter(r=>{let i=r.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:n}}function Va(e,t){let n=vr(e).filter(r=>{let i=r.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;if(typeof s!="object"||s===null)return!1;let o=s.const;return typeof o=="string"&&t.has(o)});return{...e,oneOf:n}}function ve(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function oh(e){return e.replace(/\s+/g,"-")}function Ct(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Hf(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let i=Ct(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}function Ya(e,t,n){n&&(e[t]=!0)}function Vf(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?lu(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function IE(e){let t=Vf(e.long,"long"),n=Vf(e.short,"short"),r=t??n;if(!r)return null;let i={flag:r};n&&t&&(i.short=n),Ya(i,"required",e.required===!0),Ya(i,"repeatable",e.repeatable===!0),Ya(i,"list",e.list===!0),e.default!==void 0&&(i.default=e.default);let s=Ct(e.description);s&&(i.description=s);let o=pu(e);i.value_arity=o.value_arity;let a=Ct(e.value_name)??o.value_name;a&&(i.value_name=a);let c=o.value_type??(o.value_name?"string":null);return c&&(i.value_type=c),i}function ah(e){let t=new Map;for(let r of e){let i=ve(r.target_command);if(i.length===0)continue;let s=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${r.layer}:${r.name}`;s.sourceDedupe.has(o)||(s.sourceDedupe.add(o),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=IE(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(i,s)}let n=new Map;for(let[r,i]of t.entries())n.set(r,{flags:i.flags,sources:i.sources.sort((s,o)=>{let a=s.layer.localeCompare(o.layer);return a!==0?a:(s.name??"").localeCompare(o.name??"")})});return n}function OE(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...va.filter(({flag:n})=>n.startsWith("--output-"))]}}function LE(e){let t=ah(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let o=ve(s.command);if(o.length===0)continue;let a=Ct(s.action)??oh(o),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=Ct(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:Ct(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{...s.tier===void 0?{}:{tier:s.tier},...OE(s,t.get(o)?.flags??[]),command:o,action:a,source:{layer:s.layer,name:s.name},description:Ct(s.description),intent:Ct(s.intent),arguments:c,examples:Hf(s.examples),failure_hints:Hf(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(ve(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let i=[];for(let s of[...r].sort((o,a)=>o.localeCompare(a))){let o=n.get(s);i.push(DE(s,o,t.get(s)?.flags??[]))}return i}function DE(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:oh(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function NE(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let n=t.replace(/-([a-z0-9])/g,(r,i)=>i.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return n.length>0?n:null}function ME(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 PE(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":r,...i?{items:{type:r}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function $E(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let i of e.arguments)n[i.name]=ME(i,e.action),i.required&&r.push(i.name);for(let i of e.flags){let s=NE(i);!s||n[s]!==void 0||(n[s]=va.some(o=>o.flag===i.flag&&o.flag.startsWith("--output-"))?R_[s]:PE(i,e.action),i.required===!0&&r.push(s))}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 FE(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 UE(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((s,o)=>s.localeCompare(o)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let i=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let o=`${s.flag}|${s.short??""}`;if(!i.has(o))i.add(o),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&FE(a,s)}}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 jE(e,t=x){let n={mode:Ot.extensions.policy.mode,trust_mode:Ot.extensions.policy.trust_mode,default_sandbox_profile:Ot.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=R(process.cwd(),e.path);if(!await re(Te(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(r),s=await bi({pmRoot:r,settings:i,cwd:process.cwd(),noExtensions:!1}),o=await ki({...s,loaded:s.loaded});return{handlers:new Set(o.commands.handlers.map(a=>ve(a.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function GE(e,t={}){let n=new Map;for(let r of jl){let i=ts.has(r);if(i&&!t.includePackageOwnedActions)continue;let s=Bf(r);n.set(r,{action:r,provider:i?"extension":"core",requires_extension:i,command_path:s})}if(t.includePackageOwnedActions)for(let r of ts)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Bf(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Ye.find(i=>i.alias===r.command)?.canonical??ve(r.command)});return[...n.values()].sort((r,i)=>(r.action??"").localeCompare(i.action??""))}function qE(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&&(!Gt.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?pt(e.command_path):[],r=n.some(o=>t.handlers.has(o)||t.handlers.has(H(o))),i=n.map(o=>th.get(H(o))).find(o=>typeof o=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"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 ch(e){let t=wr.get(e)??Gi,n=sr(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function KE(e){return Gt.has(H(e))?!1:wr.has(e)}function WE(e){return eh.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Yf(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function zE(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function BE(e){let t=new Map;for(let r of e.definitions){let i=Yf(r.cli_flag);if(!i)continue;let s=r.cli_aliases.map(a=>zE(a)).find(a=>a!==null),o=r.cli_aliases.map(a=>Yf(a)).filter(a=>a!==null&&a!==i);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=s?{flag:i,short:s}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let _=`${u}|`;c.seen.has(_)||(c.seen.add(_),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[r,i]of t.entries())n.set(r,wa(i.flags));return n}function Xf(e,t){let n=[],r=new Set;for(let i of[...e,...t]){let s=`${i.flag}|${i.short??""}`;r.has(s)||(r.add(s),n.push(i))}return wa(n)}function HE(e,t,n,r,i){let s=new Map(t);for(let{alias:o,canonical:a}of Ye){let c=t.get(a)??t.get(o);c&&(s.set(o,c),s.set(a,c))}return e.map(o=>{let a=KE(o),c=a?ch(o):[],d=n.get(WE(o))??[],l=s.get(o),u=Xf(c,d),_=Xf(u,l?.flags??[]),h=c.length>0&&(l?.flags.length??0)>0?"mixed":a?"core":"extension";return{command:o,flags:_,...r?{canonical_command:lh(o),visibility:dh(o,i),positionals:qm(o)?.slots??[],flag_invocations:of(o,_)}:{},provider:h,extension_sources:l?.sources}}).sort((o,a)=>o.command.localeCompare(a.command))}function VE(e,t=Lt){let n=new Set(e),r=new Map;for(let i of ih){let s=i.aliases.filter(o=>n.has(o));r.set(i.canonical,{canonical:i.canonical,aliases:s,contracts:[]})}for(let i of t){if(!n.has(i.canonical)||i.registration==="commander"&&!n.has(i.alias))continue;let s=r.get(i.canonical)??{canonical:i.canonical,aliases:[],contracts:[]};s.aliases.includes(i.alias)||s.aliases.push(i.alias),s.contracts.push(i),r.set(i.canonical,s)}return[...r.values()].map(({contracts:i,...s})=>i.length===0?s:{...s,contracts:i}).sort((i,s)=>i.canonical.localeCompare(s.canonical))}function YE(){return{create_string_options:w_,create_repeatable_options:v_,update_string_options:b_,update_repeatable_options:k_,list_string_options:__,search_string_options:f_,calendar_string_options:h_,context_string_options:g_,activity_string_options:y_}}function Jf(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=cn(e,"create",n),i=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(i.map(a=>Se("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:s,required_type_options:o,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function XE(e){let t={},n={};for(let r of[...e.types].sort((i,s)=>i.localeCompare(s))){let i=e.by_type[r];t[r]=Jf(i,"strict"),n[r]=Jf(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function JE(e,t){let n=vr(e);if(n.length===0)return e;let r=!1,i=n.map(s=>{let o=s.properties;if(typeof o!="object"||o===null)return s;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:i}:e}function QE(e){let t=es(e.action)!==void 0||es(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,i=e.schemaOnly===!0,s=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=es(e.action),l=es(e.command),u=!r&&!c&&!i&&!s&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:i,flagsOnly:s,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function ZE(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new p("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function eS(e,t=x){try{return await t(e)}catch{return structuredClone(Ot)}}async function tS(e,t,n){let r=await eS(t),i=await jE(e),s=P(r,i.registrations??M()),o=ln(r.schema),a=LE(i);return{settings:r,runtimeProbe:i,typeRegistry:s,statusRegistry:q(r.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:BE(o),createRequiredOptionContracts:XE(s),extensionContracts:a,mergedExtensionContracts:UE(a.filter(c=>ns(n,c.command,a))),extensionFlagMap:ah(i.flagRegistrations)}}function Qf(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ts.has(e.selectedAction)||e.selectedCommand!==void 0&&Gt.has(H(e.selectedCommand)))}function nS(e,t){let n=GE(t,{includePackageOwnedActions:Qf(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Gl);return n.filter(i=>!r.has(i.action)&&(e.fullOutput||(t.find(s=>s.action===i.action)?.tier??$a(i.action))!=="internal"))}return Qf(e)&&e.selectedCommand!==void 0&&Gt.has(H(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:CE(H(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function rS(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new p(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function iS(e,t){return[...new Set([...Xe.filter(n=>!Gt.has(H(n))),...[...wr.keys()].filter(n=>!Gt.has(H(n))),...e.flatMap(n=>n.command_path?pt(n.command_path).filter(r=>n.provider==="extension"||!Gt.has(H(r))||t.some(i=>i.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let i=Ye.find(s=>s.alias===r||s.canonical===r);return i===void 0?[r]:[i.alias,i.canonical]}))])].map(n=>ve(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function sS(e,t){let n=t.slice(0,kE),r=t.length-n.length,i=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,EE),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new p(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,m.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:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function oS(e,t){return new p(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.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 package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function aS(e){return new p(`Unknown command: "${e}".`,m.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 cS(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(n.length>0)throw sS(e.selectedCommand,n);let r=th.get(H(e.selectedCommand));throw r?oS(e.selectedCommand,r):aS(e.selectedCommand)}function dS(e,t){let n=nS(e,t.mergedExtensionContracts);rS(e,n);let r=iS(n,t.mergedExtensionContracts);cS(e,r);let i=e.selectedCommand?rh.get(H(e.selectedCommand)):void 0,s=e.selectedCommand?n.filter(d=>i?d.action===i:AE(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new p(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let o=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,a=[...new Map(o.map(d=>qE(d,t.runtimeProbe)).map(d=>[i?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:s,scopedActionDescriptors:o,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function lS(e){return new Set(vr(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 i=r.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function uS(e){let t=I_,n=vr(t),r=lS(t),i=e.filter(s=>!r.has(s.action)).map(s=>$E(s));return i.length>0?{...t,oneOf:[...n,...i]}:t}function Zf(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),i=e.selectedAction?RE(n,e.selectedAction):e.selectedCommand?Va(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Va(n,r);return e.runtimeOnly&&!e.selectedAction?Va(i,new Set(t.actions)):i}function mS(e,t,n){let r=uS(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?JE(Zf(e,n,r),t.createRequiredOptionContracts):Zf(e,n,r);return{mergedSchema:r,filteredSchema:i}}function pS(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?xE(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function dh(e,t){return t.find(n=>H(n.command)===H(e))?.tier??$a(e)}function ns(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||dh(t,n)!=="internal"}function _S(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Lt.filter(i=>i.hidden&&(i.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(i=>i.alias));if(e.summary&&!e.fullOutput)for(let i of Xa.keys())r.add(i);return t.filter(i=>!r.has(i)&&ns(e,i,n))}function lh(e){let t=Ye.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Xa.get(n)??n}var fS=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"]]),hS=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function gS(e,t){let n=zf.get(H(e))??(e.includes(" ")?void 0:zf.get(lh(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>pt(d.command).some(l=>H(l)===H(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 i=e.split(" "),s=i.at(-1),o=i.slice(0,-1).join(" "),a=fS.get(s),c=hS.get(e)??o;return{intent:a===void 0||o.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function yS(e,t=[],n={}){let r=n.includeFormatBudgets??!0,i=n.includeIntentProvenance??!0;return[...new Set(e.map(ve))].filter(s=>s.length>0).sort((s,o)=>s.localeCompare(o)).map(s=>{let o=ca(s,{generateFallback:!0}),a=s.split(" ")[0],c=Xa.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...ch(s).map(_=>_.flag),...t.filter(_=>pt(_.command).some(h=>H(h)===H(s))).flatMap(_=>_.flags.map(h=>h.flag))]),l=(Wf.get(H(s))??Wf.get(c)??bE).filter(_=>d.has(_)),u=gS(s,t);return{command:s,intent:u.intent,...i||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:o.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...o.default_max_estimated_tokens_by_format}}:{}}})}function wS(e){return e.map(t=>({budget:ca(t,{generateFallback:!0}),envelope:wf(t)}))}function vS(e){let t=new Map;for(let n of e){let r=Ef(n),i=r===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:r.exit_codes,s=i.join(","),o=t.get(s)??{commands:[],exit_codes:i};o.commands.push(n),t.set(s,o)}return[...t.values()]}function bS(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>pt(r.command).some(i=>H(i)===H(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(i=>pt(i.command).some(s=>r.has(s)))}return t.extensionContracts.filter(r=>ns(e,r.command,t.extensionContracts))}function kS(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 ES(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Pu);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(i=>i.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(([i])=>r===void 0||i===r).map(([i,s])=>[i,[...new Set(s.map(o=>`--${o.cli_flag}`))].sort((o,a)=>o.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Dl],services:[...Nl],policy_modes:[...Ml],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Fl],trust_modes:[...Pl],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...$l],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Hl],create_modes:[...Vl],close_validation_modes:[...Yl],workflow_enforcement_modes:[...Xl]},e.relationship_kind_contracts=[..._u,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(i=>i.definitions)].sort((i,s)=>i.kind.localeCompare(s.kind)).map(i=>({canonical:i.kind,aliases:[...i.aliases??[]],...i.inverse===void 0?{}:{inverse:i.inverse},ordering:i.ordering,hierarchy:i.hierarchy})))}function SS(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 TS(e,t,n,r,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=HE(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let s=new Set(r);e.list_projections=Object.entries(em).filter(([o])=>s.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...Zu,"priority"],compact_fields:[...Qu]}))}e.command_aliases=t.fullOutput?i:i.map(({canonical:s,aliases:o})=>({canonical:s,aliases:o})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function CS(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=YE();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function AS(e,t,n,r){e.command_summaries=yS(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Bu],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(ve))].filter(i=>Yu(i)!==void 0).sort((i,s)=>i.localeCompare(s)).map(i=>({command:i,modes:[...Xu(i).keys()]}))}:{}},e.grammar_contracts={nouns:jt.nouns,shared_verbs:jt.shared_verbs,scope_before_verb:jt.scope_before_verb,visible_top_level_ceiling:jt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:jt.ceiling_raise_requires_pm_item,positional_shape_budget:jt.positional_shape_budget,positional_shape_count:new Set(ya.map(({slots:i})=>Wm(i))).size,positional_action_count:ga.length,positional_action_parents:[...new Set(ga.map(({parent:i})=>i))].sort((i,s)=>i.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:ya}:{}}}async function W1(e,t){let n=QE(e);ZE(n);let r=R(process.cwd(),t.path),i=await tS(t,r,n),s=dS(n,i),o=mS(n,i,s),a=pS(n,s),c=_S(n,a,i.extensionContracts),d=kS(n,o,s,c),l=bS(n,i,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&AS(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let _=VE(s.commandCatalog.filter(h=>ns(n,h,i.extensionContracts)));return n.flagsOnly&&!n.fullOutput||ES(d,i,n),SS(d,n,o,l),TS(d,n,i,c,_),CS(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...fr],gate_triggers:[...ut]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=Km.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Kf(),d.context_intents=Ju(),d.read_output_dimensions=Vu,d.error_codes=gf,d.command_output_contracts=wS(c),d.diagnostic_output_contracts=Hu,d.command_exit_contracts={vocabulary:Ua,command_sets:vS(c)}),d}import{readFile as xS}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();function oU(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Je(e,t)}function uh(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new p(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function RS(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function qt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function aU(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=Q(n,"--add");return Object.keys(i).map(s=>s.trim().toLowerCase()).some(s=>s!=="text")?n:i.text?.trim()||n}catch{return n}}function IS(e){return typeof e=="object"&&e!==null&&"code"in e}function mh(e,t){if(!Dt(e))throw new p(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function OS(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new p(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=on(),r=Dt(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return mh(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new p("--file path cannot be empty",m.USAGE);if(i==="-")return mh(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await xS(i,"utf8"),emptyFlag:"--file"}}catch(s){if(IS(s)&&an(s))throw new p(`--file path not found: ${i}. Use --file - to read stdin.`,m.USAGE);let o=s instanceof Error?s.message:String(s);throw new p(`Failed to read --file path "${i}": ${o}. Use --file - to read stdin.`,m.USAGE)}}async function cU(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new p("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new p("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new p("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new p("--edit must be a positive integer",m.USAGE);let n=await OS(e,t);if(e.edit!==void 0){if(!n)throw new p("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function br(e,t){throw e instanceof p&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new p(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function _h(e){return e==="comments"?"--stdin":"--add -"}function LS(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let n=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(n))return;let r=_h(t.collectionKey),i=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new p(`--add value "${n}" looks like an option, not annotation text. Use ${r} to read stdin, or use text=${n} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${r} for stdin input, pass plain text, or use text=${n} when the text really starts with "-".`,examples:[`${i} ${r}`,`${i} --add text=${n}`]})}function DS(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new p(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.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 p(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.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> ${_h(e.collectionKey)}`]})}function NS(e,t,n,r,i,s){let o=qt(e.metadata,t),a=i?o.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(o.push(s({created_at:I(),author:n,text:r})),e.metadata[t]=o,{changedFields:[t],entryIndex:o.length})}async function dU(e,t,n,r){DS(r,t);let i=R(process.cwd(),n.path);await F(i);let s=await x(i),o=P(s,M()),a=ir(t.limit);if(r.input.mode==="list"){let f=await V(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!f)throw new p(`Item ${e} not found`,m.NOT_FOUND);let g=await ue(f,{schema:s.schema}),y=qt(g.document.metadata,r.collectionKey);return rs(f.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=U(t.author,s.author_default);if(r.input.mode==="delete"){let f=r.deleteOp??r.op,g;try{g=await me({pmRoot:i,settings:s,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=qt(w.metadata,r.collectionKey),k=ph(r.input.index,b.length,r.collectionKey);return uh(b[k],"deleted"),b.splice(k,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){br(w,r.conflictGuidance)}let y=qt(g.item,r.collectionKey);return rs(g.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";LS(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new p(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(r.input.mode==="edit"){let f=r.editOp??r.op,g;try{g=await me({pmRoot:i,settings:s,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=qt(w.metadata,r.collectionKey),k=ph(r.input.index,b.length,r.collectionKey),C=b[k];return uh(C,"edited"),b[k]={...C,text:l,edited_at:I()},w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){br(w,r.conflictGuidance)}let y=qt(g.item,r.collectionKey);return rs(g.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let u,_=0;try{u=await me({pmRoot:i,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(f){let g=NS(f,r.collectionKey,c,l,t.ifAbsent===!0,r.createEntry);return _=g.entryIndex,{changedFields:g.changedFields}}})}catch(f){br(f,r.conflictGuidance)}let h=qt(u.item,r.collectionKey);return rs(u.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"add",entryIndex:_,entry:h[_-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function ph(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),i=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new p(`${i} index ${e??"(missing)"} out of range (item has ${s})`,m.USAGE)}return e-1}function MS(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 rs(e,t,n,r,i,s,o=!1){let a=s===void 0||o?RS(n,s!==void 0&&o?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[i,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...MS(t,s,c)}}import{createHash as hh}from"node:crypto";import kr from"node:fs/promises";import Er 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]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function je(e,t){throw new p(e,m.USAGE,t)}var PS="2026-07-15T06:22:12.276Z",$S=Date.parse(PS),FS=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],fh=e=>typeof e=="string"?e:"",gh=e=>{let t=e??{},n=fh(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(fh(t.ts))>=$S);return FS[r][i]};function yh(e,t,n=20,r=new Set,i=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[_,h]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(h)}catch{continue}d+=1;let g=gh(f);if(g!=="attributed"){if(l+=1,g==="actionable_unknown"&&r.has(`${e}:${_+1}`)){u+=1;continue}a[g]+=1,i&&g==="actionable_unknown"&&o.push({item_id:e,line:_+1}),s.length<c&&s.push({item_id:e,line:_+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var wU=(e,t,n=20,r=new Set)=>yh(e,t,n,r);function wh(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let s of i.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var Sr=async(e,t=20,n=!1)=>{let r=Er.join(e,"history"),i;try{i=(await kr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,b)=>w.localeCompare(b))}catch{i=[]}let s=new Set,o=[],a=[],c=0,d=0,l=0,u=0,_=0,h=0,f="_workspace.jsonl",g=new Set;if(i.includes(f))try{g=wh(await kr.readFile(Er.join(r,f),"utf8"))}catch{g=new Set}for(let w of i){let b;try{b=await kr.readFile(Er.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),C=yh(k,b,t-o.length,g,n);c+=1,d+=C.checked_events,l+=C.unknown_event_count,u+=C.legacy_unknown_event_count,_+=C.actionable_unknown_event_count,h+=C.acknowledged_actionable_event_count,C.unknown_event_count>0&&s.add(k),o.push(...C.samples),n&&a.push(...C.actionable_events)}let y=u+_;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:_,acknowledged_actionable_event_count:h,affected_item_ids:[...s].sort((w,b)=>w.localeCompare(b)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};function US(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function jS(e){try{return wh(await kr.readFile(Er.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function GS(e){return(e.item_id===Pt||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function qS(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{je(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return gh(i)!=="actionable_unknown"&&je(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:hh("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function vh(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&je("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&je("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&je("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=US(t.all_actionable===!0?(await Sr(e,0,!0)).actionable_events:r),o=await jS(e),a=new Map;for(let _ of s)if(GS(_)||je(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(_.item_id))try{a.set(_.item_id,(await kr.readFile(Er.join(e,"history",`${_.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{je(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(_=>qS(_,o,a.get(_.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=hh("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:_})=>_==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function vU(e,t,n=50){return(await vh(e,t,n)).plan}function KS(e,t){let n=e.length>0;return n&&t&&je("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&je("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:WS(e),all_actionable:t}}function WS(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),s=r===Pt||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!s||!Number.isSafeInteger(i)||i<1)&&je(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function bU(e,t){let n=KS(L_(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return zS(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:ee(t,"planFingerprint")??ee(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:ee(t,"attributedAuthor")??ee(t,"attributed_author")??void 0,reviewer:ee(t,"reviewer"),reason:ee(t,"reason")})}async function zS(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",s=await vh(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:m.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&je("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||je("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==s.plan.plan_fingerprint)throw new p("Author acknowledgment selection changed after preview; no history was mutated.",m.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let o=s.completeCoordinates.filter(({disposition:l})=>s.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(o.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:m.NO_EFFECT,plan:s.plan};let a=await x(e),c=await pn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:r}},message:i,lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms}),d=s.plan.actionable_count>0&&s.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:o.length,...d,plan:s.plan,history_path:c.historyPath}}import HS from"node:fs/promises";import Ae from"node:path";import{glob as VS}from"tinyglobby";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var BS=/^[a-z][a-z0-9+.-]+:\/\//i;function Tr(e){return BS.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var YS=["path","scope","note"],XS=["pattern","glob","path","scope","note"],JS=["path"],QS=["from","to"],ZS=new Set(["note","scope"]);function kh(e){let t=e??"project";if(!Fe.includes(t))throw new p(`Invalid scope "${e}". Valid scopes: ${Fe.join(", ")} (default: project).`,m.USAGE);return t}function Ja(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||sn(e)}function eT(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function tT(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Ja(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let s=e.slice(t+2,-1).trim();if(s.length>0&&eT(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function nT(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let s=tT(r);if(s!==void 0)return[s]}Hn(r,"--add",`${t} path`,Ja(r));let i=Ja(r)?Q(n,"--add"):{path:r};if(we(i,"--add",YS),!i.path)throw new p(`--add requires path=<value> or a bare ${t} path`,m.USAGE);return[{path:i.path,scope:kh(i.scope),note:i.note?.trim()||void 0}]}):[]}function rT(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--add-glob requires a glob pattern value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=Q(n,"--add-glob");we(r,"--add-glob",XS);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new p("--add-glob key/value form requires pattern=<glob>",m.USAGE);return{pattern:i,scope:kh(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function iT(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires a path value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=Q(n,"--remove"),i=Object.keys(r).filter(s=>ZS.has(s.toLowerCase()));if(i.length>0)throw new p(`--remove identifies a linked artifact by path only and does not accept ${i.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,m.USAGE);if(we(r,"--remove",JS),!r.path)throw new p("--remove key/value form requires path=<value>",m.USAGE);return r.path}return n}):[]}function sT(e){return e?e.map(t=>{let n=Q(t,"--migrate");we(n,"--migrate",QS);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new p("--migrate requires from=<value> and to=<value>",m.USAGE);return{from:r,to:i}}):[]}function Cr(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function oT(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(s=>Cr(s.path,n))),i=[...new Set(t.map(s=>Cr(s,n)).filter(s=>r.has(s)))].sort((s,o)=>s.localeCompare(o));if(i.length!==0)throw new p(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,m.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function _t(e){return e.split(Ae.sep).join("/")}function Qa(e,t,n=process.cwd()){let r=e.trim();if(Tr(r))return r;if(Ae.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return _t(r.replaceAll("\\",Ae.sep));let i=Ae.relative(t,n);return i.startsWith(`..${Ae.sep}`)||i===".."||Ae.isAbsolute(i)?_t(Ae.normalize(r)):_t(Ae.relative(t,Ae.resolve(n,r)))}async function aT(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Ae.resolve(n,i.pattern)===Ae.resolve(n))continue;let s=Ae.isAbsolute(i.pattern),o=await VS(i.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>Qa(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of a)r.push({path:c,scope:i.scope,note:i.note})}return r}function cT(e,t,n){if(t===void 0)return e;if(!n)throw new p("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",m.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function dT(e){return`${e.path}::${e.scope}`}function Za(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function ec(e){return[...new Map(e.map(t=>[dT(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function lT(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],i=[],s=[],o=[];for(let a of n){if(Tr(a)){o.push(a.trim());continue}let c=Ae.isAbsolute(a)?a:Ae.resolve(t,a);try{(await HS.stat(c)).isFile()?r.push(a):s.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&an(d)){i.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:s,remote_references:o}}function uT(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let o=Cr(e[s].path,r);o!==e[s].path&&(e[s]={...e[s],path:o},i+=1)}return{adds:t.map(s=>{let o=Cr(s.path,r);return o!==s.path&&(i+=1),{...s,path:o}}),removes:n.map(s=>Cr(s,r)),count:i}}function mT(e,t,n,r){let i=ec(e);for(let s of t){let o=i.findIndex(a=>a.path===s.path&&a.scope===s.scope);o<0?i.push(s):s.note!==void 0&&(i[o]={...i[o],note:s.note})}if(n.length>0)for(let s=i.length-1;s>=0;s-=1)n.includes(i[s].path)&&i.splice(s,1);return r?i:Za(i)}async function bh(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await lT(t,e.workspaceRoot):void 0}}async function is(e,t,n,r){let{metadataKey:i}=r,s=on(),o=R(process.cwd(),n.path),a=Qe(o),c=process.cwd();await F(o);let d=await x(o),l=P(d,M()),u=await s.resolveList(t.add,"--add"),_=await s.resolveList(t.addGlob,"--add-glob"),h=await s.resolveList(t.remove,"--remove"),f=await s.resolveList(t.migrate,"--migrate"),g=nT(u,r.bareNoun).map(N=>({...N,path:Qa(N.path,a,c)})),y=rT(_),w=await aT(y,a,c),b=cT([...g,...w],t.note,g.length>0||y.length>0),k=iT(h).map(N=>Qa(N,a,c)),C=sT(f);if(oT(b,k,C),!(b.length>0||k.length>0||C.length>0)){let N=await V(o,e,d.id_prefix,d.item_format,l.type_to_folder);if(!N)throw new p(`Item ${e} not found`,m.NOT_FOUND);let E=(await ue(N,{schema:d.schema})).document.metadata[i]??[];return bh({id:N.id,artifacts:E,changed:!1,options:t,workspaceRoot:a})}let S=U(t.author,d.author_default),A=await me({pmRoot:o,settings:d,id:e,op:r.op,author:S,message:t.message,force:t.force,skipNoop:!0,mutate(N){let E=N.metadata,$=E[i]??[],he=[...$],ce=uT(he,b,k,C),de=mT(he,ce.adds,ce.removes,r.supportsAppendStable&&t.appendStable===!0);de.length>0?E[i]=de:delete E[i];let _e=!$e($,de);return{changedFields:_e?[i]:[],warnings:_e&&ce.count>0?[`path_migrations_applied:${ce.count}`]:[]}}}),v=A.item[i]??[],T=A.warnings.find(N=>N.startsWith("path_migrations_applied:")),L=T?Number(T.slice(24)):0;return bh({id:A.item.id,artifacts:v,changed:A.changedFields.includes(i),migrationsApplied:L,options:t,workspaceRoot:a})}function ss(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function Eh(e,t,n){let r=await is(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ss(r,"docs")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67d97df8-6551-52ed-9307-8b573a087831")}catch{}})();var os=1e6;function tc(e,t=os,n=.8,r=!1){let i=new Set,s=(l,u)=>{if(i.add(`${l}:${u}`),i.size>t)throw new p(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(r||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return i}let o=new Map;for(let{prepared:l}of e)for(let u of l.tokens)o.set(u,(o.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let _=[...u.tokens].sort((g,y)=>o.get(g)-o.get(y)||g.localeCompare(y)),h=_.length-Math.ceil(n*_.length-1e-12)+1,f=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:_.length===0?[""]:_.slice(0,h),lengthFilter:!0}];for(let g of f)pT(e,l,g,n,s)}return i}function pT(e,t,n,r,i){let s=e[t].prepared.tokens.length;for(let o of n.keys){let a=n.index.get(o)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<r||i(c,t)}a.push(t),n.index.set(o,a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5f450bd-8970-5b1b-8250-b76b7818e6e1")}catch{}})();var _T=3,Sh=20,fT=.8,hT=100,Th=1e3;function Ch(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function gT(e,t){let n=e.items[0],r=R(t.cwd??process.cwd(),t.pmRoot),i=q((await x(r)).schema);return fe(n.status,i)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function nc(e){let t=e.limit??_T,n=e.threshold??fT;if(!Number.isSafeInteger(t)||t<0||t>Sh)throw new p(`Similarity limit must be an integer from 0 to ${Sh}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new p("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function Ah(e){let t=e.limit??hT;if(!Number.isSafeInteger(t)||t<0||t>Th)throw new p(`Duplicate cluster limit must be an integer from 0 to ${Th}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new p("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function yT(e,t){let n=R(e.cwd??process.cwd(),e.pmRoot),r=await x(n),i=P(r),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new p("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let o=q(r.schema),a=s?.map(u=>{if(u==="all")return u;let _=se(u,o);if(!_)throw new p(`Unknown duplicate-cluster status "${u}". Allowed: all, ${o.definitions.map(h=>h.id).join(", ")}.`,m.USAGE);return _}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new p('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await Ee(n,r.item_format,i.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var cj={buildDuplicateClusters:Rh,collectDuplicateCandidatePairs:tc,createDuplicateUnionFind:xh};function xh(e){let t=Array.from({length:e},(n,r)=>r);return{parent:t,findRoot:n=>{let r=n;for(;t[r]!==r;)r=t[r];for(;t[n]!==n;){let i=t[n];t[n]=r,n=i}return r}}}function wT(e,t,n,r){let i=[];for(let s of t){let[o,a]=s.split(":").map(u=>Number.parseInt(u,10)),c=fa(e[o].prepared,e[a].prepared);if(c.score<n)continue;let d=r.findRoot(o),l=r.findRoot(a);d!==l&&(r.parent[l]=d),i.push({left_id:e[o].item.id,right_id:e[a].item.id,...c})}return i}function Rh(e,t,n,r){let i=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=i.get(c)??[];d.push(a),i.set(c,d)}let s=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),o=new Map;for(let a of t){let c=s.get(a.left_id),d=o.get(c)??[];d.push(a),o.set(c,d)}return[...i.values()].filter(a=>a.length>1).map(a=>{let c=(o.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,r)}function vT(e,t,n,r,i){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,..._a(e,s.title)})).filter(s=>s.score>=r).sort((s,o)=>o.score-s.score||s.id.localeCompare(o.id)).slice(0,i)}async function bT(e,t={}){let n=e.title.trim();if(n.length===0)throw new p("Similarity candidate title must not be empty.",m.USAGE);let{limit:r,threshold:i}=nc(t),s=R(t.cwd??process.cwd(),t.pmRoot),o=await x(s),a=P(o),c=await $i(s,Object.values(a.type_to_folder)),d=ma(n),l=c&&d.length>0?await ym({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(h=>`"${h.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await Ee(s,o.item_format,a.type_to_folder,void 0,o.schema):l.items,_=vT(n,u,new Set(e.excludeIds??[]),i,r);return{items:_,count:_.length,threshold:i,source:l?"persistent_index":"metadata_fallback"}}function kT(e,t={}){let{threshold:n}=nc({...t,limit:void 0}),{limit:r}=Ah(t),i=new Set;for(let l of e){if(!l.id.trim()||i.has(l.id))throw new p("Duplicate analysis requires unique non-empty item ids.",m.USAGE);i.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:pa(l.title)})),o=tc(s,os,n,t.exhaustive===!0),a=xh(s.length),c=wT(s,o,n,a),d=Rh(s,c,a,r);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:os,recall_guarantee:"exact",candidate_pairs:o.size,scored_pairs:o.size}}}async function Ih(e={}){nc({...e,limit:void 0});let{since:t}=Ah(e),{items:n,statuses:r}=await yT(e,t);return{...kT(n,e),source:"metadata_scan",filters:{statuses:r??null,since:e.since??null}}}async function rc(e,t){if(t.mode==="off")return;let n=await bT(e,t);if(n.count===0)return;let r=await gT(n,t),i=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!i){let s=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),o=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new p(`Likely duplicate item(s) found: ${s}. ${o} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${o}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:i,result:n,recovery:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();async function mj(e,t={}){let n=await Ih({pmRoot:R(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(r=>{let i=r.id;return{...r,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as ET}from"node:child_process";import Oh 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]="3bb613e2-51f9-5947-8d92-d6207bb62cdc")}catch{}})();function Lh(e,t){return new Promise((n,r)=>{ET("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,s)=>{i?r(i):n(s)})})}function Dh(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function gj(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Dh(n),!n)throw new RangeError("Source line range must use start:end.");return n}function ST(e){let t=new Map;for(let n of e.split(`
|
|
7
|
+
`)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function TT(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let s=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,a)=>o.localeCompare(a));n.set(i,s)}return n}async function CT(e){let t=Oh.relative(e.workspaceRoot,Oh.resolve(e.workspaceRoot,e.sourcePath)),n=await Lh(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Lh(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:ST(n),commitItems:TT(r),available:!0}}function AT(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let s=i.source===t,o=s?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,s?i.kind:a.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function xT(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let s=t.shift(),o=s.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=AT({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((s,o)=>s.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function RT(e,t,n){let r=F_(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=xT({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),s=i[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:o.slice(1)}}async function IT(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await CT({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function OT(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function LT(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Nh(e){Dh(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await IT(e),r=LT(n),i=new Map;for(let s of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),a=o.reduce((l,[,u])=>l+u,0),c=RT(s.item.id,e.corpus,t),d=OT({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(s.item.id,{score:a*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import Mh from"node:fs/promises";import Ge 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]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();var DT=32768;function ic(e){return _t(Ge.normalize(e))}async function as(e){try{return await Mh.realpath(e)}catch{return Ge.resolve(e)}}function An(e,t){let n=Ge.isAbsolute(e.path)?Ge.resolve(e.path):Ge.resolve(t,e.path);return`${ic(n)}::${e.scope}`}function cs(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>cs(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))cs(i,t?`${t}.${r}`:r,n)}function NT(e){let t=[];return cs(e.metadata,"metadata",t),cs(e.body,"body",t),t}function MT(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function PT(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let s=new Set,o=i.value.slice(0,DT);for(let[a,c]of[[n,i.value],[r,o]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=MT(d[0]);!l||s.has(l)||(s.add(l),t.push({field:i.field,value:l}))}}}return t}async function $T(e,t,n=t){let r=Ge.isAbsolute(e)?Ge.resolve(e):Ge.resolve(n,e),i;try{i=await Mh.stat(r)}catch{return}if(!i.isFile())return;let[s,o]=await Promise.all([as(t),as(r)]);if(na(s,o)){let a=Ge.relative(s,o);return!a||a.startsWith("..")||Ge.isAbsolute(a)?void 0:{path:ic(a),scope:"project"}}return{path:ic(r),scope:"global"}}async function FT(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>An(c,t))),i=new Map,s=PT(NT(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await $T(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=An(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function Ph(e,t,n){let r=await is(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ss(r,"files")}async function UT(e,t){let n=await as(t),r=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new p("Files lookup paths must not be empty.",m.USAGE);if(!Ge.isAbsolute(o))return _t(o);let a=await as(o);return na(n,a)?_t(Ge.relative(n,a)):_t(a)})),i=[...new Set(r)].sort((s,o)=>s.localeCompare(o));if(i.length===0)throw new p("Files lookup requires at least one path.",m.USAGE);return i}function jT(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new p(`Files lookup ${r} must be a non-negative integer.`,m.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function $h(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Fh(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function GT(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(_t(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(Fh)}async function qT(e){if(e.explain)return Nh({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function KT(e){if([e.strictRead,e.noTruncate,e.explain,ku()].includes(!0))return null;let t=await $i(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?gm({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function WT(e){let t=[],n=await Fi(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=GT({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(a=>/^item_list_(?:item|directory)_read_failed:/u.test(a));if(e.strictRead&&i.length>0)throw new p(`Files lookup could not read every item: ${i.join("; ")}`,m.GENERIC_FAILURE);let s=await qT({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),o=(s?[...r].sort((a,c)=>{let d=s.explanations.get(c.item.id).score-s.explanations.get(a.item.id).score;return d!==0?d:Fh(a,c)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:o.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+o.length<r.length,truncated:e.offset+o.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:o.map(a=>({item:$h(a.item),files:a.files,...s?{traceability:s.explanations.get(a.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function Mj(e,t){let n=R(process.cwd(),t.path),r=Qe(n);await F(n);let i=await UT(e.paths,r);if(e.lineRange&&i.length!==1)throw new p("Files lookup line attribution requires exactly one source path.",m.USAGE);let s=await x(n),o=P(s,M()),{offset:a,limit:c}=jT(e),d=await KT({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:$h(l.item),files:l.files}))}:WT({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function Pj(e,t,n){let r=R(process.cwd(),n.path),i=Qe(r);await F(r);let s=await x(r),o=P(s,M()),a=await V(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new p(`Item ${e} not found`,m.NOT_FOUND);let c=await ue(a,{schema:s.schema}),d=await FT(c.document,i,process.cwd()),l=d.filter(T=>T.status==="addable"),u=d.filter(T=>T.status==="already_linked"),_=t.apply===!0,h=t.note?.trim()||"discovered from item text";if(!_||l.length===0){let T=c.document.metadata.files??[];return{id:a.id,files:T,changed:!1,apply:_,count:T.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=U(t.author,s.author_default),g=l.map(T=>({path:T.path,scope:T.scope,note:h})),y=[],w=new Set,b=await me({pmRoot:r,settings:s,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(T){let L=[...T.metadata.files??[]],N=new Set(L.map(he=>An(he,i)));y=[],w.clear();for(let[he,ce]of g.entries()){let de=An(ce,i);N.has(de)||(L.push(ce),N.add(de),y.push(ce),w.add(he))}let E=ec(L),$=t.appendStable?E:Za(E);return $.length>0?T.metadata.files=$:delete T.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==g.length?[`files_discover_skipped_existing:${g.length-y.length}`]:[]}}}),k=b.item.files??[],C=new Set(y.map(T=>An(T,i))),S=k.filter(T=>C.has(An(T,i))),A=l.filter((T,L)=>!w.has(L)),v=[...u,...A];return{id:b.item.id,files:k,changed:S.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:S.length,skipped_existing_count:v.length,candidates:d,added:S,skipped_existing: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]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var Ar=["software-delivery","research","agent-evaluation","operations"];function Uh(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function ds(e,t,n,r,i){let s=`preset-${e}`,o=i.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=o.map(c=>Uh(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:a,gates:[{id:`${s}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function ls(e,t){return e==="software-delivery"?ds(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?ds(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?ds(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):ds(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function jh(e,t,n,r={}){return Ha(e,ls(t,n).declarations,r)}async function Gh(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let s={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},o=(await Ba(s,r)).value,a=Uh(`${s.id}-ceiling`,s.id,t,o,"observe"),c=`active-missing-${i}`;return{id:c,population_size:r.items.length,scope:{kind:"active"},observed:o,declarations:{measurements:[s],assertions:[a],gates:[{id:`derived-${c}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[a.id],triggers:["ci","scheduled"]}]}}}))}function qh(e,t,n={}){return Ha(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function Kh(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return Zi(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Bh from"node:fs/promises";import{createRequire as zT}from"node:module";import De 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]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function Wh(e,t){let n=De.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${De.sep}`)&&!De.isAbsolute(n))return n.split(De.sep).join("/");let r=De.resolve(e),i=0xcbf29ce484222325n;for(let s=0;s<r.length;s+=1)i^=BigInt(r.charCodeAt(s)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${De.basename(De.dirname(e))}/package.json`}function BT(e){return e.includes(`${De.sep}.pnpm${De.sep}`)?"pnpm":e.includes(`${De.sep}node_modules${De.sep}`)?"npm":"other"}async function zh(e){try{let t=JSON.parse(await Bh.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function sc(e){try{return await Bh.realpath(e)}catch{return De.resolve(e)}}async function Hh(e,t,n=gu(import.meta.url,["../../.."])){let r=await sc(t),i=await sc(De.join(n,"package.json")),s=await zh(i),o=new Map;s!==void 0&&o.set(i,{version:s,path:Wh(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=zT(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await sc(l),_=await zh(u);if(_===void 0)continue;let h=u,f=o.get(h);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((g,y)=>g.localeCompare(y)));continue}o.set(h,{version:_,path:Wh(u,r),layout:BT(u),consumers:[d.name]})}catch{}let a=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:a.filter(d=>d.version!==s);return{host_version:s??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${s}:${d.version}:${d.consumers.join("+")}`)}}import{createHash as HT}from"node:crypto";import us 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]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var VT="2026-08-09T16:15:18.000Z",Yh=Symbol("pre-durable-disposition-eligible");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oc(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Vh(e){return ft(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function Xh(e,t){if(typeof e!="string")return!1;let n=us.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!us.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(us.posix.basename(n)===`${t}.toon`||us.posix.basename(n)===`${t}.md`)}function YT(e,t){return typeof e.receipt_id=="string"&&pr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Xh(e.item_path,t)}function Jh(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,s=Array.isArray(i)?new Set(i.flatMap(o=>Vh(o)?[o.field]:[])):new Set;return oc(t)&&oc(n)&&oc(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Vh)&&s.size===i.length&&t.length===s.size&&t.every(o=>s.has(o))}function XT(e,t){return YT(e,t)&&Jh(e)}function JT(e,t){return typeof e.receipt_id=="string"&&pr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Xh(e.item_path,t)&&Jh(e)}function QT(e){return e[Yh]===!0}function Qh(e,t){if(!ft(e)||!ft(e.context))return[];let n=e.context.merge;return!ft(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!ft(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:XT(r,t),[Yh]:JT(r,t),...typeof e.ts=="string"&&ia(e.ts)?{eventTimestamp:e.ts}:{}}])}function Zh(e,t,n){if(!ft(e)||e.op!=="merge_reconcile")return[];if(!ft(e.context)||!ft(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!ft(i)||typeof i.receipt_id!="string"||!pr(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!ia(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function eg(e,t,n=[]){let r=new Map;for(let s of n){let o=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;r.set(o,Math.max(r.get(o)??0,s.auditHistoryLine))}let i=s=>QT(s)&&s.eventTimestamp!==void 0&&wi(s.eventTimestamp,VT)<0&&(r.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!i(s)).map(s=>({item_id:s.itemId,history_line:s.line,...pr(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:HT("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).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]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function ms(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,a)=>o.localeCompare(a)),i=new Set(r),s=t.filter(o=>{let a=Ke(o.status,e);return a!==void 0&&i.has(a)}).map(o=>o.id).sort((o,a)=>o.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:s.length,affected_item_ids:s.slice(0,n),affected_item_ids_truncated:s.length>n}}function ps(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="717434ef-3c62-50a8-8887-e2bbc3851eff")}catch{}})();var ng=8,ac=100;function rg(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function We(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function ZT(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function xr(e,t){let n=We(e,t);return{...n,sample:n.sample.map(r=>ZT(r))}}function z(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function eC(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var tC={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:z(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:z(e.missing_required,t),missing_optional:z(e.missing_optional,t),missing:z(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:z(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:xr(e.discovered,t),effective:xr(e.effective,t),loaded:xr(e.loaded,t),failed:We(e.failed,t),warnings:z(e.warnings,t),activation:{failed:We(n.failed,t),warnings:z(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:eC(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:We(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:z(n.affected_item_ids,t),samples:We(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:z(e.item_unreadable,t),item_conflict_markers:We(e.item_conflict_markers,t),item_parse_failures:z(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:z(n.tracked_paths,t)},history_unreadable:z(e.history_unreadable,t),history_conflict_markers:We(e.history_conflict_markers,t),history_invalid_json:We(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:z(n.candidate_items,t),confirmed_items:z(n.confirmed_items,t),resolved_false_positive_items:z(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:z(e.drifted_items,t),merge_receipt_attributed_items:z(e.merge_receipt_attributed_items,t),missing_streams:z(e.missing_streams,t),unreadable_streams:z(e.unreadable_streams,t),hash_mismatches:z(e.hash_mismatches,t),chain_mismatches:z(e.chain_mismatches,t),version_skews:z(e.version_skews,t),workspace_state_mismatches:z(e.workspace_state_mismatches,t),workspace_state_missing:z(e.workspace_state_missing,t),workspace_state_unreadable:z(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:z(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:z(e.stale_items_after,t),skipped:e.skipped})};function cc(e,t){let n=tC[e.name];return n?n(e.details,t):e.details}function ig(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function nC(e){if(e.name==="extensions"&&e.status==="ok")return ig(e);let t=cc(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function dc(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function rC(e){let t=z(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:nC(n)})),warnings:t.sample,findings:dc(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function tg(e){return e.details.skipped===!0}function iC(e){let t=z(e.warnings,8),n=e.checks.filter(tg).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!tg(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:dc(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function sC(e,t,n){return t.full===!0?e:n?iC(e):t.brief===!0?rC(e):{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:ig(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function lc(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),s={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:dc(e,i)},o=sC(s,t,n);return{...o,warning_count:r,warning_limit:100,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}import ht from"node:fs/promises";import xe from"node:path";import xn from"node:fs/promises";import Rr 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]="b01042e0-77ae-5e2c-8118-6680f0002d60")}catch{}})();function sg(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:s,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof s!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:s,ttl_seconds:o,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function oC(e,t,n){let r=sg(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-i,o=Math.floor(s/1e3),a=s>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function og(e,t,n){let r=oC(e,t,n);if(r.detail!=="active")return r;let i=sg(t),s=await Fu(i);return s==="unknown"?r:{detail:s==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:s,pid:i.pid,...s==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function aC(e,t,n){let r=await ju(e,"gc");if(r===null)return!1;try{let i;try{i=await xn.readFile(e,"utf8")}catch(s){if(j(s))return!0;throw s}if(i!==t)return!1;n&&await Gu(e,t);try{await xn.unlink(e)}catch(s){if(!j(s))throw s}return!0}finally{await r()}}function cC(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function ag(e,t){let n=t??Date.now(),r=Rr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await xn.readdir(r)).filter(o=>o.endsWith(".lock")).sort()}catch(o){if(j(o))return i;throw o}for(let o of s){let a;try{a=await xn.readFile(Rr.join(r,o),"utf8")}catch(l){if(j(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:d}=await og(o,a,n);cC(i,c,d)}return i}async function dC(e,t,n,r,i,s,o){if(!t.dryRun){try{if(!await aC(n,s,o.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${i}`),e.retained.push(r),e.entries.push(o);return}}catch{e.warnings.push(`lock_remove_failed:${i}`),e.retained.push(r),e.entries.push(o);return}if(t.hooks?.onWrite){let a=await t.hooks.onWrite(n);e.warnings.push(...a)}}e.removed.push(r),e.entries.push(o)}async function cg(e,t){let{hooks:n}=t,r=t.now??Date.now(),i=Rr.join(e,"locks"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await $u(e,Rr.join(i,"gc.lock"),"gc");let o;try{o=(await xn.readdir(i)).filter(a=>a.endsWith(".lock")).sort()}catch(a){if(j(a))return s;throw a}for(let a of o){s.scanned+=1;let c=Rr.join(i,a),d=`locks/${a}`;if(n?.onRead){let _=await n.onRead(c);s.warnings.push(..._)}let l;try{l=await xn.readFile(c,"utf8")}catch(_){if(j(_)){s.scanned-=1;continue}s.warnings.push(`lock_unreadable:${a}`),s.retained.push(d),s.entries.push({file:a,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await og(a,l,r);if(u.detail==="unparseable_json"){s.warnings.push(`lock_unparseable:${a}`),s.retained.push(d),s.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){s.warnings.push(`lock_invalid_timestamp:${a}`),s.retained.push(d),s.entries.push(u.entry);continue}if(u.detail==="active"){s.retained.push(d),s.entries.push(u.entry);continue}await dC(s,t,c,d,a,l,u.entry)}return 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]="0e576e9d-5aa3-5d54-8acf-23e4f18b432f")}catch{}})();var lC=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function uc(e){if(typeof e!="string")return;let t=e.trim();for(let n of lC)if(t===n.code||t.startsWith(`${n.code}:`))return n}function mc(e){let t={};for(let n of e){let r=uc(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function dg(e){return Object.values(mc(e))}import{execFile as uC}from"node:child_process";import{realpath as mC}from"node:fs/promises";import lg from"node:path";import{promisify as pC}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]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var _C=pC(uC),fC=32*1024*1024,hC=1e4,gC=["search/eval-queries.json"];function pc(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function yC(e){return`'${e.replaceAll("'","'\\''")}'`}async function wC(e,t=mC){return t(e).catch(()=>lg.resolve(e))}async function _s(e){let t=await Tt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await wC(e),r=pc(lg.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=j_.map(s=>`${r}/${pc(s)}`);try{let{stdout:s}=await _C("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:fC,windowsHide:!0,timeout:hC}),o=new Set(gC.map(d=>`${r}/${d}`)),a=[...new Set(s.split("\0").filter(d=>d.length>0&&!o.has(pc(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>yC(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import ug from"node:path";import{realpath as vC}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]="7637003b-61ed-52eb-849c-eaf098df2963")}catch{}})();async function mg(e,t){let n=t===null?[]:await Z_(t,[ug.relative(t,ug.join(await vC(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function pg(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await wn(e,yn(n));if(i.status==="ok")return{audit:i,count:0,warnings:[]};let s=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:s,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${s}`]:[]}}function _g(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),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]="11486e17-e6da-5770-8621-f59a17bb4922")}catch{}})();var bC=new Set(Am),fg=25,kC=xe.join("runtime","telemetry","events.jsonl"),EC=xe.join("runtime","telemetry","state.json"),SC=2500,TC=500,hg=Dm-3,CC=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function wc(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function vc(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Rn(e){return e.trim().toLowerCase()}function hc(e,t){let n=Rn(e),r=Rn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function bc(e){try{return(await ht.stat(e)).isDirectory()}catch{return!1}}async function AC(e){let t=(await ht.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>ht.readdir(xe.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Nt.some(s=>i.name.endsWith(s))).map(i=>xe.parse(i.name).name)))}async function xC(e,t,n,r){let i=await Ue({path:e,scope:"project"}),s=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!s)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await ht.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(s){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function RC(e,t,n){let r=xe.join(e,"history");if(!await bc(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await ht.readdir(r)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),s=t.enabled?t.max_entries:null,o=[],a=[],c=[],d=[];for(let l of i){let u=xe.join(r,l),_=l.slice(0,-6),h=await xC(u,_,t,n);o.push(...h.warnings),h.classification==="tombstone"&&c.push(_),h.classification==="orphaned"&&d.push(_),h.overThreshold&&a.push(_)}return{count:i.length,warnings:[...o,...a.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:a,max_entries:s,tombstones:c,orphaned:d}}function gc(e,t){return xe.relative(e,t).replaceAll("\\","/")}async function gg(e,t){let n=[...new Set(Object.values(t))].sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=xe.join(e,i),o=[];try{o=await ht.readdir(s)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&j(a))continue;continue}for(let a of o)Nt.some(c=>a.toLowerCase().endsWith(c))&&r.push(xe.join(s,a))}return r.sort((i,s)=>gc(e,i).localeCompare(gc(e,s))),r}function IC(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function OC(e,t,n){let r=await gg(e,t),i=[],s=[],o=[],a=[],c=kt(M());for(let d of r){let l=gc(e,d),u;try{u=await ht.readFile(d,"utf8")}catch{i.push(l);continue}let _=un(u);if(_){s.push({path:l,..._});continue}try{let h=Ri(u,{format:eu(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:Ai(h.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:s,parseFailures:o,formatVersions:a}}async function LC(e){let t=xe.join(e,"history"),n=[],r=[],i=[],s=[],o=[],a=[];try{a=(await ht.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){IC(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await ht.readFile(xe.join(t,c),"utf8")}catch{n.push(d);continue}let u=un(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((_,h)=>{if(_.trim())try{let f=JSON.parse(_);s.push(...Qh(f,d).map(g=>({itemId:d,line:h+1,...g}))),o.push(...Zh(f,d,h+1))}catch{i.push({id:d,line:h+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:s,mergeReceiptDispositions:o}}function yg(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function DC(e,t,n,r,i,s){let o=await OC(e,t,n),a=await LC(e),c=xi(o.formatVersions,er,Ci),d=q(n),l=zi(s,E=>fe(E,d),oe()),u=await _s(e),_=await Tt(e),h=await mg(e,_),f=await pg(e,_,r,i),g=_===null?null:await vn(_),y=await bn(_??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),b=eg(a.mergeReceiptReferences,w,a.mergeReceiptDispositions),k=b.missing,C=y.receipts.filter(E=>E.state==="pending"),{pendingDecisions:S,lossless:A}=kn(C),v=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,T=[...o.unreadable.map(E=>`integrity_item_unreadable:${E}`),...o.conflictMarkers.map(E=>`integrity_item_conflict_marker:${E.path}:L${E.line}`),...o.parseFailures.map(E=>`integrity_item_parse_failed:${E}`),...a.unreadable.map(E=>`integrity_history_unreadable:${E}`),...a.conflictMarkers.map(E=>`integrity_history_conflict_marker:${E.id}:L${E.line}`),...a.invalidJson.map(E=>`integrity_history_invalid_json:${E.id}:L${E.line}`),...c.outdated.map(E=>`integrity_item_outdated_format_version:${E}`),...c.ahead.map(E=>`integrity_item_ahead_format_version:${E}`),...yg(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${v?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...f.warnings,...h.warnings,...S.length>0?[`merge_decisions_unreviewed:${S.length}`]:[],...A.length>0?[`merge_receipts_pending:${A.length}`]:[],..._g({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:k.length})],L=[...new Set(T)].sort((E,$)=>E.localeCompare($)),N=L.filter(E=>!E.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:N.length===0?"ok":"warn",ok:N.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:f.count,ignored_merge_artifacts:h.rules.length,pending_merge_decisions:S.length,lossless_merge_receipts:A.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:k.length,accepted_legacy_merge_receipt_references:b.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:b.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:We(l.relations,ng)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:i},merge_fence:f.audit,ignored_merge_artifacts:h.rules,pending_merge_decision_items:[...new Set(S.map(E=>E.item_id))].sort((E,$)=>E.localeCompare($)),lossless_merge_receipt_items:[...new Set(A.map(E=>E.item_id))].sort((E,$)=>E.localeCompare($)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:k.slice(0,ac),missing_merge_receipt_history_reference_details_truncated:k.length>ac}},warnings:L,gitWorkspaceRoot:_,pendingMergeReceipts:C}}function NC(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function MC(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:NC(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function PC(e,t){return ie(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function $C(e){let t=ie(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function FC(e){return ie(e.reason)??ie(e.error)??ie(e.message)}function _c(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function UC(e){let t=[],n=[],r=[];e.forEach((s,o)=>{let a=PC(s.definition,o),c=$C(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:a,status:c});return}if(c==="failed"){r.push({layer:s.layer,name:s.name,id:a,status:c,reason:FC(s.definition)});return}n.push({layer:s.layer,name:s.name,id:a,status:c})}),t.sort(_c),n.sort(_c),r.sort(_c);let i=[...r.map(s=>`extension_migration_failed:${s.layer}:${s.name}:${s.id}`),...n.map(s=>`extension_migration_pending:${s.layer}:${s.name}:${s.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function wg(e,t,n,r,i,s,o,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>vc(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,_=c.length>0,h=_?"partial":"full",f=d.map(La).filter(y=>y!==void 0),g=z_(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&f.push(g),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${Tl.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),_?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:s,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:h,update_health_partial:_,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function jC(e,t,n){let r=await B_(Qe(e)),i=await bi({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=i.loaded.map(v=>MC(v)),o=await Hh(i.loaded,Qe(e)),a=await ki({...i,loaded:i.loaded}),[c,d]=await Promise.all([Oa(i.roots.project),Oa(i.roots.global)]);await Gm(e,a.registrations.migrations);let l=UC(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},_=new Set(c.state.entries.map(v=>Rn(v.name))),h=new Set(d.state.entries.map(v=>Rn(v.name))),f=[...new Map(i.loaded.filter(v=>!(v.layer==="project"?_:h).has(Rn(v.name))).map(v=>[`${v.layer}:${v.name}`,{layer:v.layer,name:v.name,directory:v.directory}])).values()].sort((v,T)=>{let L=`${v.layer}:${v.name}`,N=`${T.layer}:${T.name}`;return L.localeCompare(N)}),g=f.map(v=>`${v.layer}:${v.name}`).sort((v,T)=>v.localeCompare(T)),y=f.filter(v=>hc(v.name,v.directory)).map(v=>`${v.layer}:${v.name}`).sort((v,T)=>v.localeCompare(T)),w=f.filter(v=>!hc(v.name,v.directory)).map(v=>`${v.layer}:${v.name}`).sort((v,T)=>v.localeCompare(T)),b=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...b,...o.warnings],C=Da(k),S=Na(),A=wg(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,g,y,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:s,warnings:k,activation:u,author_manifest:r,triage:A,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:S,capability_guidance:C,host_version_census:o}},warnings:k}}function yc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=rg(e,fg);return{values:n.values,truncated:n.truncated,total:e.length}}function fs(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function GC(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return bC.has(e)?e:null}function hs(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function vg(e){let t=0,n=0,r=0,i=0,s=0;for(let o of e.split(`
|
|
8
|
+
`)){let a=o.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=hg&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:s}}function qC(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function KC(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function WC(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Ft().telemetry_disabled?void 0:{attempted:!0,...await bg(n)}}function zC(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,s=n.last_failed_flush_at,o=s&&(!i||s>i),a=!i,c=t.validEntries>=TC;return(o||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function BC(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function HC(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Lm?[`telemetry_schema_version_behind:${t}`]:[]}function VC(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function YC(){return{...Ft(),pm_no_telemetry:fs("PM_NO_TELEMETRY"),telemetry_otel_disabled:fs("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:fs("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:GC()}}function XC(e,t){return e.telemetry.enabled&&t.validEntries>0}function JC(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function bg(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(SC)});return{probe_url:hs(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of CC){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:hs(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function QC(e,t){let n=qe(process.cwd()),r=xe.join(n,kC),i=xe.join(n,EC),s=await Z(r),o=s!==null,a=s?Buffer.byteLength(s,"utf8"):0,c=s?vg(s):qC(),d=await Z(i),{runtimeState:l,stateParseFailed:u}=KC(d),_=e.telemetry.endpoint.trim(),h=hs(_),f=await WC(e,t.checkTelemetry),g=[];u&&g.push("telemetry_state_invalid_json"),g.push(...zC(e,c,l),...BC(f),...HC(f),...VC(e,l));let y=XC(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:g.length===0?"ok":"warn",ok:g.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:h,global_pm_root:n,queue_path:r,queue_exists:o,queue_entries:c.validEntries,queue_draining:JC(y,g),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:hg,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:f??{attempted:!1},env_overrides:YC()}},warnings:g}}async function ZC(e){let t;try{t=await ag(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function eA(e){let t="metadata",n=e.items,r=await mr(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,b)=>w.localeCompare(b)),s=[],o=[];if(i.length>0){n=await lt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await mr(e.pmRoot,n),s=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((b,k)=>b.localeCompare(k));let w=new Set(s);o=i.filter(b=>!w.has(b))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:_,workspaceStateMismatches:h,workspaceStateMissing:f,workspaceStateUnreadable:g}=r,y=[...a.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...h.map(w=>`history_drift_workspace_state_mismatch:${w}`),...f.map(w=>`history_drift_workspace_state_missing:${w}`),...g.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:s,resolved_false_positive_items:o,authoritative_item_source:i.length>0},drifted_items:_,counts:{drifted:_.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:h.length,workspace_state_missing:f.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:h,workspace_state_missing:f,workspace_state_unreadable:g}},warnings:y}}function tA(e,t){let n=pm(e),r=km(n.settings),i=Em(n.settings,t),s=r.active?Sm(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(r.active&&i.active)}}function nA(){return{refreshed:[],skipped:[],warnings:[]}}async function rA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?nA():Cm(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function iA(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Tm(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function sA(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function oA(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function kg(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:la(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:la(r,e.vector_store?.adapter??null)}}function aA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function cA(e,t,n){return e.enabled&&n.length>0&&t}async function dA(e,t,n,r,i){let s=tA(t,e),o=await ua(e),a=s.semanticRuntimeAvailable?Pa(n,o.entries):[],c=await rA({pmRoot:e,snapshot:s,refreshPolicy:r,staleBefore:a}),d=await ua(e),l=s.semanticRuntimeAvailable?Pa(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,_=iA({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),h=sA({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:_,staleAfter:l}),f=yc(a,i),g=yc(l,i),y=cA(r,s.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:h.length===0?"ok":"warn",ok:h.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:aA(r),...kg(t,s),embedding_identity_changed:_,embedding_identity_before:o.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:fg,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:y,refresh_skipped_reason:oA(r,s.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:h}}function lA(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Eg(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new p("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new p("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var uA=new Set(["extensions","locks","search"]);function mA(e){let t=new Set(xl.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Rl));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of uA)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,s)=>i.localeCompare(s)),optionalDirs:[...n].sort((i,s)=>i.localeCompare(s)),optionalDirSet:n}}async function pA(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:s}=mA(t),o=[],a=[],c=[];for(let d of[...r,...i]){let l=xe.join(e,d);c.push(...await Ue({path:l,scope:"project"})),!await bc(l)&&(s.has(d)?a.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function Sg(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function _A(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Ee(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):lt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function fc(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function fA(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function hA(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function gA(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var kc=e=>e.unknown_event_count??0,Ec=e=>e.actionable_unknown_event_count??kc(e);function yA(e,t,n,r,i,s){let o=kc(r),a=Ec(r),c=o>0,d=a>0,l=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:r}:{},...l?{stale_in_progress:i}:{},...s.outcomes.length>0?{provenance_resolver_outcomes:s.outcomes}:{},...s.invalid_values.length>0?{provenance_invalid_values:s.invalid_values}:{},provenance_sample:s.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Tg(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function wA(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function vA(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function bA(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Cg(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let s of i)t.has(s)||t.set(s,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",s=uc(r)?.code??vc(r),o=n.get(i)?.details,a=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=La(r)??(s==="agent_guidance_outdated"?"pm init --agent-guidance add":s==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":a[s]),d=wc(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:s,check:i,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function kA(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function EA(e){for(let t of e.checks){let n=mc(e.remediationSources[t.name]);kA({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function SA(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){let a=i.get(o.item_id)??[];a.push(o),i.set(o.item_id,a)}let s=[];for(let o of n){if(r.has(o))continue;let a=i.get(o);if(!(!a||a.length===0))try{await ef(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),s.push(o)}catch{}}return[...new Set(s)].sort((o,a)=>o.localeCompare(a))}function TA(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function Ag(e,t={}){let n=R(process.cwd(),e.path);await F(n);let r=Te(n),{settings:i,warnings:s}=await um(n),o=[...new Set(s)],a=P(i,M()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Eg(t),_=await pA(n,a,c),h=lA(i),f=await QC(i,{checkTelemetry:t.checkTelemetry===!0}),g=await jC(n,i,!!e.noExtensions),y=Sg(t),w=[],b=await _A({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:w}),k=b,C=ms(q(i.schema),b),S=[...(await H_({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(Y=>Y.startsWith("agent_guidance_")),...h,...ps(C)],A=y.skipDrift?{warnings:[]}:await Ii({pmRoot:n,settings:i,itemIds:b.map(Y=>Y.id),commandLabel:"health"}),v=await RC(n,i.history.compact_policy,await AC(n)),T=await Sr(n,20,t.verboseAuthorEvents===!0),L=Ec(T),N=L>0?[`history_unknown_author_events:${L}`]:[],E=Tg(await Im(n,b,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),$=await Q_(n),he=$.warnings,ce=await ZC(n),de=y.skipIntegrity&&!l?{...fc("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await DC(n,a.type_to_folder,i.schema,i,l,b),_e=y.skipDrift?fc("history_drift"):await eA({pmRoot:n,items:k,settings:i,typeRegistry:a,itemReadWarnings:w}),rn=[...new Set(w)],Bn=await SA({gitWorkspaceRoot:de.gitWorkspaceRoot,pendingMergeReceipts:de.pendingMergeReceipts,historyDriftCheck:_e,global:e});TA(_e,Bn);let rt=y.skipVectors?fc("vectorization"):await dA(n,i,k,u,t.verboseStaleItems===!0),Ne=[fA(r,i,o),hA(_,c),gA(S,C),f.check,g.check,yA(b,i,v,T,E.scan,$),ce.check,de.check,_e.check,rt.check],yt=wA({directoryState:_,normalizedSettingsReadWarnings:o,settingWarnings:S,normalizedItemReadWarnings:rn,telemetryCheck:f,extensionCheck:g,historyPolicyWarnings:A.warnings,historySummary:v,authorAttributionWarnings:N,staleInProgressWarnings:E.warnings,provenanceWarnings:he,locksCheck:ce,integrityCheck:de,historyDriftCheck:_e,vectorizationCheck:rt}),ke=bA({directoryState:_,normalizedSettingsReadWarnings:o,settingWarnings:S,normalizedItemReadWarnings:rn,telemetryCheck:f,extensionCheck:g,historyPolicyWarnings:A.warnings,historySummary:v,authorAttributionWarnings:N,staleInProgressWarnings:E.warnings,provenanceWarnings:he,locksCheck:ce,integrityCheck:de,historyDriftCheck:_e,vectorizationCheck:rt});EA({checks:Ne,remediationSources:ke,historyDriftedCount:vA(_e),overThresholdCount:v.over_threshold.length});let Me=yt.filter(Y=>!wc(Y,l)),wt=Cg({warnings:yt,checks:Ne,remediationSources:ke,requireMergeDrivers:l}),O=new Set(wt.filter(Y=>Y.severity==="gate_failing").map(Y=>Y.check)),it=new Set(wt.map(Y=>Y.check));for(let Y of Ne)Y.ok=!O.has(Y.name),it.has(Y.name)&&(Y.status="warn");let vt={ok:Me.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Me.length>0?m.GENERIC_FAILURE:0},checks:Ne,warnings:yt,findings:wt,failed_because:Me,generated_at:I()};return lc(vt,t,y.summaryMode)}var gq={buildHierarchyIntegrityWarnings:yg,buildExtensionHealthTriageSummary:wg,buildHealthFindings:Cg,buildCapabilityContractMetadata:Na,buildStaleInProgressHealthSummary:Tg,buildVectorizationProviderDetails:kg,collectUnknownCapabilityGuidance:Da,isAdvisoryHealthWarning:wc,isDirectory:bc,isExpectedUnmanagedExtension:hc,listItemDocumentPaths:gg,normalizeEndpointForDisplay:hs,normalizeExtensionNameForMatch:Rn,parseTelemetryQueue:vg,probeTelemetryEndpointHealth:bg,projectHealthResult:lc,resolveActionableUnknownAuthorEventCount:Ec,resolveHealthSkipPolicy:Sg,resolveUnknownAuthorEventCount:kc,resolveVectorRefreshPolicy:Eg,selectStaleItemDetail:yc,summarizeHealthCheckDetails:cc,summarizeExtensionList:xr,summarizeRecordList:We,summarizeStringList:z,telemetryEnvFlagEnabled:fs,warningCode:vc};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function xg(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!jm(e,t).ok)return{reason:"unverified_history"};let r=im(),i={reason:"no_proven_transition"};for(let[s,o]of e.entries()){let a=n.has(String(r.metadata.status));r=_m(r,o.patch,s+1,o.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&mu(o.ts)?{timestamp:o.ts,source_index:s+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Rg(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function Ig(e,t,n,r,i){let s=Rg(n),o=t.filter(d=>s.has(d.status)&&!d.closed_at),a=[],c=[];for(let d of r?o:[]){let l;try{let u=await dt(ot(e,d.id),d.id),{body:_,...h}=d;l=xg(u,{metadata:h,body:_},s)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}a.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function Og(e,t){let n=R(process.cwd(),t.path),r=await x(n),i=q(r.schema);await me({pmRoot:n,settings:r,id:e.item_id,op:"update",author:U(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(s){if(s.metadata.closed_at)return{changedFields:[]};let o=await dt(ot(n,s.metadata.id),s.metadata.id),a=Rg(i),c=xg(o,s,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new p("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",m.GENERIC_FAILURE);return s.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function CA(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Lg(e){return`${e.item_id} ${e.link_kind}`}function Dg(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=CA(i.classification,r.classification),i.owners.set(Lg(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Lg(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function Ng(e,t,n,r,i=40){let s=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,o=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Dg(e,n).map(d=>{let l=[],u=[];for(let h of d.items){let f=se(h.status,r)??h.status;r.terminal_statuses.has(f)?(u.push(h),f===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(h)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let _=o.get(d.path);return{...d,candidates:_?.candidates??[],candidates_truncated:_?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,s),a.missing_linked_path_rows_truncated=c.length>s,a}import In from"node:fs/promises";import On 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]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function AA(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let s;try{s=await In.readdir(On.join(e,i))}catch{return}for(let o of s)for(let a of Nt)if(o.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-a.length)});break}})),r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath))}function xA(e,t){let{id:n,relativePath:r,liveItemIds:i,out:s}=e,o=un(t);if(o){s.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=RA(e,t);a!==null&&(a.op==="delete"&&i.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function RA(e,t){let{id:n,relativePath:r,out:i}=e,s=null,o=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(s.op==="create"){if(o)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return s}function Sc(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function IA(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await In.readdir(On.join(e,"history"))}catch{return n}for(let i of r.sort((s,o)=>s.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await In.readFile(On.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Sc("history stream",o)});continue}xA({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},s)}return n}function Mg(e){let t=un(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function OA(e){let t=[],n=0,r=null;try{r=await Z(Te(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Sc("configuration file",s)})}if(r!==null){n+=1;let s=Mg(r);s!==null&&t.push({path:"settings.json",detail:s})}let i;try{i=await In.readdir(On.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of i.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await In.readFile(On.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Sc("configuration file",c)});continue}let a=Mg(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function Pg(e,t,n,r={}){let i=await AA(e,n),s=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let _=o.get(u.id);_===void 0?o.set(u.id,[u.relativePath]):_.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,_])=>({id:u,paths:[..._].sort((h,f)=>h.localeCompare(f))})).sort((u,_)=>u.id.localeCompare(_.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let _=On.join(e,u.relativePath);return Ri(await In.readFile(_,"utf8"),{format:_.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await IA(e,s),l=await OA(e);return{item_files_on_disk:i.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{readFileSync as LA}from"node:fs";import gs 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]="d88c7294-44f1-5b65-9467-f94ed2db11ca")}catch{}})();var DA=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ac=new Set(["--pm-path","--path","--author","--expect-hash"]),NA={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},MA=new Set(["-p","--package"]),PA=new Set(["-c","--call"]),xc=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Rc=new Set(["-C","--prefix","--userconfig","--cache"]),$g=new Set(["--cwd"]),Fg=new Set(["--cwd"]),$A=new Set(["exec","x"]),Ug=new Set(["run","run-script"]),jg=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Kt(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function vs(e,t=process.cwd()){let n=bs(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(ys(r)||ws(r,t))return i;if(r==="node"&&i[0]&&ws(i[0],t))return i.slice(1);let s=r==="npx"||r==="bunx"?Wt(i):r==="pnpm"?ks(i):r==="npm"?Es(i):null;return s&&(ys(s.command)||Gg(s.command))?s.args:null}var Ic=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of Kt(s)){let c=vs(a),d=c?Oc(c):null,l=d&&DA.has(d.subcommand)?UA(d.remaining,NA[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function bs(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Cc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ac.has(n)){t+=2;continue}t+=1;continue}return n}}function ys(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function FA(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function Gg(e){let t=FA(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function ws(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=gs.resolve(t,e);try{return JSON.parse(LA(gs.join(gs.dirname(gs.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Wt(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let s=i[1];return s?{command:s,args:e.slice(t+1)}:null}if(PA.has(r)){t+=1;break}t+=MA.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function At(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function ks(e){let t=At(e,xc);return t?.subcommand!=="dlx"?null:Wt(t.args)}function Es(e){let t=At(e,Rc);return!t||!$A.has(t.subcommand)?null:Wt(t.args)}function Oc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ac.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function UA(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Ac.has(r)||t.has(r))&&(n+=1)}}function Tc(e){return!e||!ys(e.command)&&!Gg(e.command)?!1:Cc(e.args)==="test-all"}var Lc=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])]),jA=new Set(["npx","bunx"]);function Dc(e){let t=e.split(" ").filter(o=>o.length>0),n=bs(t);if(n.length===0)return!1;let[r,...i]=n,s=Lc.get(r);if(s){let o=i.findIndex(a=>s.test(a));return o>=0?Dc(i.slice(o+1).join(" ")):!1}return ys(r)||ws(r)?Cc(i)==="test-all":r==="node"&&i.length>0&&ws(i[0])?Cc(i.slice(1))==="test-all":jA.has(r)?Tc(Wt(i)):r==="pnpm"?Tc(ks(i)):r==="npm"?Tc(Es(i)):!1}function Nc(e){let t=Ln(e);return Kt(t).some(n=>Dc(n))}function Ir(e){if(Nc(e))throw new p('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function Ln(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as GA}from"node:child_process";import{readFile as qA}from"node:fs/promises";import Kg from"node:path";import{promisify as KA}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]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var WA=KA(GA),Mc=1,zA="linked-test-trust.json";function Pc(e){return Kg.join(tu(e),zA)}function qg(){return{version:Mc,acknowledged:{}}}async function $c(e){try{let t=JSON.parse(await qA(Pc(e),"utf8"));return t.version!==Mc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?qg():{version:Mc,acknowledged:t.acknowledged}}catch{return qg()}}async function Lr(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await WA("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Dr(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function BA(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&uu(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Or(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function HA(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function Dn(e,t,n){if(!e||e.length===0)return e;for(let i of e)Jn(i);let r=Dr();return HA(e,t,n,await Lr(r))}function Wg(e){return Ol(ne({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function Fc(e,t,n){let r=await $c(e);return zg(t,n,r)}function zg(e,t,n){let r=Wg(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!BA(e.provenance)?s?{fingerprint:r,trusted:!0,reason:"acknowledged",...Or(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...Or(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...Or(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:s?{fingerprint:r,trusted:!0,reason:"acknowledged",...Or(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...Or(i,t)}}async function Bg(e,t,n){let r=await $c(e);return t.map(i=>zg(i,n,r))}async function Hg(e,t,n){let r=await $c(e),i=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(Wg);for(let s of i)r.acknowledged[s]={acknowledged_at:n};return await bt(Kg.dirname(Pc(e))),await Le(Pc(e),`${JSON.stringify(r,null,2)}
|
|
9
|
+
`),{acknowledged:i.length,fingerprints:i}}import Qc from"node:fs/promises";import{realpathSync as rx}from"node:fs";import{execFile as ix}from"node:child_process";import Re from"node:path";import{promisify as sx}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]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var VA=["metadata","resolution"],Uc=["metadata","resolution","estimates","timestamps","lifecycle"],YA="completed";function jc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Vg(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Yg(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Vg(n.close_reason)??YA;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${jc(r)}`,gate:"resolution"})}return t}function Xg(e){let t=[];for(let n of e){let r=Vg(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${jc(r)}`,gate:"metadata"})}return t}function Jg(e,t){return e.map(n=>{let r=lm(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function Qg(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Zg(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${jc(n.path)}`})}return t}function ey(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new p(`--fix-scope values must not be empty. Supported values: ${Uc.join(", ")}.`,m.USAGE);return new Set(VA)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Uc.includes(i)){n.add(i);continue}throw new p(`Unknown --fix-scope value "${r}". Supported values: ${Uc.join(", ")}.`,m.USAGE)}return n}function ty(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Nr(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var XA=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function JA(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=XA.exec(n);if(!r)return null;let i=r[1],s=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(o.toUpperCase())||l?s:null}function ny(e){return typeof e=="string"&&e.trim().length>0}function QA(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,r=new Map;for(let o of e){let a=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(d=>d!==a&&t.has(d)));n.set(a,c);for(let d of c){let l=r.get(d)??[];l.push(a),r.set(d,l)}}let i=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],s=new Set;for(let o=0;o<i.length;o+=1)for(let a of r.get(i[o])??[]){let c=n.get(a);c.delete(i[o]),c.size===0&&(s.add(a),i.push(a))}return e.filter(o=>!s.has(o.id.toLowerCase()))}function ry(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||ny(i.duplicate_of))continue;let s=JA(i.title,{...t,evidenceText:i.body});if(s===null)continue;let o=n.get(s);o||(o=[],n.set(s,o)),o.some(a=>a.id===i.id)||o.push({id:i.id,title:i.title,parent:ny(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,s]of n){if(s.length<2)continue;let o=QA(s);if(o.length<2)continue;let a=[...o].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,s)=>i.code.localeCompare(s.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function iy(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,s)=>i.localeCompare(s))){let i=t.get(r),s={};for(let o of[...i.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=i.get(o);n[r]=s}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]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function sy(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function oy(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let s of t){let o=sy(s);if(o.length===0)continue;let a=i.get(o);a?a.push(s):i.set(o,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(i.get(sy(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function ay(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function Ss(e){return e.includeBody?lt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Fi(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.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]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var ZA=5;async function ex(e,t){let n=t.hashMismatches.filter(s=>s!==Pt);if(n.length===0)return;let r=await x(e),i=P(r,M());for(let s of n){let o=await mn(e,s,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await V(e,s,r.id_prefix,r.item_format,i.type_to_folder);if(a===null)throw new p(`Item ${s} not found`,m.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await ue(a,{schema:r.schema});if(c.metadata.id!==s)throw new p(`Item identity changed while validating ${s}`,m.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await J_(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(_=>_!==s),...d[u].filter(_=>_===s)].sort((_,h)=>_.localeCompare(h));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==s),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===s)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function Ts(e,t,n){let r=await mr(e,t);await ex(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),s=n?Number.POSITIVE_INFINITY:ZA,o=r.driftedItems.slice(0,s),a=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:a.length>0?"error":i.length===0?"ok":"warn",ok:a.length===0&&i.length===0,details:{identity_discontinuities:a.slice(0,s),identity_discontinuities_count:a.length,identity_discontinuities_truncated:a.length>s,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:o,drifted_items_truncated:o.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings: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]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function Cs(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],s=new Set([n]),o=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!s.has(c)){if(s.add(c),i.push(c),o(c))return!0;i.pop(),s.delete(c)}}return!1};return o(n)?[...i]:[...e,n]}function tx(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function nx(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let s=r.resolve(i.kind);if(!s?.hierarchy)continue;let o=n.get(i.id.toLowerCase());o&&(s.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function Gc(e,t=oe()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((s,o)=>s.id.localeCompare(o.id))){let s=r.get(i.id),o=tx(i.parent,n);o&&s.push(o),nx(i,r,n,t)}for(let[i,s]of r)r.set(i,[...new Set(s)].sort());return r}function qc(e,t,n=oe()){let r=zi(e,o=>t?Et(o,t):o==="closed"||o==="canceled",n),i=Gc(e,n),s=r.cycles.map(o=>o.item_ids);return{cycle_count:s.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(o=>Cs(o,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function xt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Kc(e){return xt(e).replace(/\/+$/,"")}function ze(e){let t=ie(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Wc(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`: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]="3ff209da-9855-53ee-8ae4-8c6ec7d5f964")}catch{}})();var ox=["src","tests","docs"],ax=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],cx=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),dx=["resolution","expected_result","actual_result"],lx=["default","tracked-all","tracked-all-strict"],cy=["core","strict","custom"],Rs=["off","warn","error"],Hc=["author","acceptance_criteria","estimated_minutes","close_reason"],uy=[...Hc,"reviewer","risk","confidence","sprint","release"],Vc=Array.from(new Set(uy)),ux={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"},mx={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},px={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},_x={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},fx={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},hx=32*1024*1024,gx=1e4,Yc=40,Be=5,yx=4096,wx=255,vx=sx(ix);function my(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?my(r):r);return t}function bx(e){return{...e,checks:e.checks.map(t=>({...t,details:my(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Os(e,t){return se(e,t)??e}function Mr(e,t){return t.terminal_statuses.has(Os(e,t))}function Rt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function As(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function kx(e){let t=Rt(Il),n={blocked_reason:Rt(si.blocked_reason),resolution:Rt(si.resolution),actual_result:Rt(si.actual_result)},r=Rt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Rt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Rt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Rt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:As(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:As(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:As(i.resolution,n.resolution)?"default":"settings",actual_result:As(i.actual_result,n.actual_result)?"default":"settings"}}}function py(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(cy.includes(t))return t;throw new p(`Unknown --metadata-profile value "${e}". Supported values: ${cy.join(", ")}.`,m.USAGE)}function _y(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Rs.includes(t))return t;throw new p(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Rs.join(", ")}.`,m.USAGE)}function fy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Rs.includes(t))return t;throw new p(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Rs.join(", ")}.`,m.USAGE)}function Ex(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>ux[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function Sx(e,t,n){let r=Ex(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Hc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...uy],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Hc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Tx=new Set(["acceptance_criteria","estimated_minutes"]);function hy(e,t,n,r){return!r&&Tx.has(t)&&Mr(e.status,n)?!1:t==="author"?!ie(e.author):t==="acceptance_criteria"?!ie(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Os(e.status,n)===n.close_status&&!ie(e.close_reason):t==="reviewer"?!ie(e.reviewer):t==="risk"?!ie(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ie(e.confidence):t==="sprint"?!ie(e.sprint):!ie(e.release)}function gy(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new p(`Unknown --scan-mode value "${e}". Supported values: ${lx.join(", ")}.`,m.USAGE)}function yy(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Re.resolve(t);let n=Re.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Re.dirname(Re.dirname(n));let r=Re.resolve(process.cwd()),i=dy(n),s=dy(r),o=Re.relative(i,s);return o.length===0||!o.startsWith("..")&&!Re.isAbsolute(o)?n:r}function dy(e){try{return rx.native(e)}catch{return Re.resolve(e)}}function Cx(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Zc(e,t,n){let r=t.length>0?Re.join(e,t):e,i;try{i=await Qc.readdir(r,{withFileTypes:!0})}catch(s){if(j(s))return;throw s}for(let s of i){if(s.name.startsWith("."))continue;let o=t.length>0?Re.join(t,s.name):s.name;if(s.isDirectory()){if(cx.has(s.name))continue;await Zc(e,o,n);continue}s.isFile()&&n.push(xt(o))}}async function Xc(e){let t=[];for(let n of ox)await Zc(e,n,t);for(let n of ax){let r=Re.join(e,n);try{(await Qc.stat(r)).isFile()&&t.push(xt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function wy(e){try{let{stdout:t}=await vx("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:hx,windowsHide:!0,timeout:gx}),n=t.split("\0").map(r=>xt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function Ax(e,t){let n=new Set,r=Kc(Al);r.length>0&&n.add(r);let i=Kc(Re.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((s,o)=>s.localeCompare(o))}function ly(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function xx(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await wy(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Xc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Xc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function te(e,t=Be){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function zt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=te(e,Yc);return{values:n.values,truncated:n.truncated,total:e.length}}var Rx={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},Ix={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function Ox(e){let t=e.missing_fields.map(n=>`${Rx[n]} "${Ix[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function vy(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):dg(t);if(i.length===0)return;let s=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...s?{fix_hints_truncated:!0}:{}}}function by(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var Lx="validate_metadata_duplicate_issue_codes";function ky(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Be,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${Lx}:${e.length}`]}}function Dx(e,t,n){let r=Object.fromEntries(Vc.map(i=>[i,[]]));for(let i of e)for(let s of Vc)hy(i,s,t,n)&&r[s].push(i.id);return r}function Nx(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let s=t[i];s.length>0&&r.push(`${mx[i]}:${s.length}`)}return r.push(...n),r}function Ey(e,t){let n={};for(let r of e.required_fields){let i=t[r],s=i?i.length:0,o=px[r];n[o]=s}return n}function Sy(e,t,n){let r=[];for(let i of e.required_fields){let s=t[i];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function Mx(e,t,n,r){for(let i of t.required_fields){let s=n[i];if(!s||s.length===0)continue;let o=_x[i],a=fx[i];if(!o||!a)continue;let c=te(s,r?s.length:Be);e[o]=c.values,e[a]=c.truncated}}function Ty(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:ie(n.get(i)?.resolution)})):[]}function Cy(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:ie(n.get(i)?.type)})):[]}function Px(e,t,n,r,i){let s=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",a=Dx(e,n,o),c=ry(e,{configuredPrefixes:i}),d=ky(c,r),l=Nx(t,a,d.warnings),u=Ey(t,a),_=Sy(t,a,s),h=iy(_),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Vc],counts:u,missing_by_type:h,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),Mx(f,t,a,r);let g=Ty(t,a,s),y=Cy(t,a,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:g,estimateBackfillRows:y}}function $x(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(_=>r.has(Os(_.status,t))),s=[],o=[];for(let _ of i){let h=dx.filter(f=>!ie(_[f]));h.length!==0&&(s.push({id:_.id,missing_fields:h}),o.push({id:_.id,missing_fields:h,close_reason:ie(_.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:Be,d=te(s.map(_=>`${_.id}:${_.missing_fields.join(",")}`),c),l=s.map(_=>Ox(_)),u=te(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function Ay(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xy(e,t="pm",n=fu()){let r=new Set(e.map(s=>s.id)),i=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(i.map(s=>{let o=new Set,a=ze(s.blocked_by);a&&r.has(a)&&o.add(a),(s.dependencies??[]).filter(d=>{let l=ze(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>ze(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=ze(s.definition_of_ready);return Iy(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[s.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function Ry(e,t,n){let r=$_(e,n?l=>Mr(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:Be,a=te(i,o),c=te(s,o),d=te(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+s.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function Iy(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Ay(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,s)=>i.localeCompare(s))}function Oy(e){let t=0,n=new Map,r=new Map,i=[],s=new Set,o=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),s.add(d);for(let u of e.get(d)??[])n.has(u)?s.has(u)&&r.set(d,Math.min(r.get(d),n.get(u))):(a(u),r.set(d,Math.min(r.get(d),r.get(u))));if(r.get(d)!==n.get(d))return;let l=[];for(;i.length>0;){let u=i.pop();if(s.delete(u),l.push(u),u===d)break}l.sort((u,_)=>u.localeCompare(_)),o.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||a(d);return o.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}function Ly(e,t="pm"){let n=xy(e,t),r=Oy(n),i=[...new Set(r.flat())].sort((o,a)=>o.localeCompare(a)),s=r.map(o=>Cs(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:s}}function Dy(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Is(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Ny(e,t){let n=Is(e).split("/").filter(Boolean),r=Is(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function Fx(e,t){let n=Is(t),r=Is(e),i=t.endsWith("/")?t:`${t}/`,s=e.startsWith(i),o=n.length>0&&n===r,a=Ny(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function Ux(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function jx(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(s=>(r==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=xt(o.path);if(a.length===0||a===e)return;let c=Fx(e,a);c!==null&&Ux(i,s,c.score)&&(i={item:s,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function My(e,t){return e.map(n=>{let r=Dy(n),i=r==="docs_unowned"?"docs":"files",s=jx(n,r,t),o=s?.id??"<id>";return{path:n,classification:r,owner_candidate:s,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Py(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function Gx(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=ze(e[n]);return i?r.some(s=>i.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function qx(e,t,n,r,i){let s=ze(t.parent),o=s?n.get(r.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Mr(o.status,i)}}function Kx(e,t,n,r){let i=ze(e.blocked_by),s=ze(e.blocked_reason),o=s?.toLowerCase(),a=Os(e.status,n),c=[];return t.has(a)?(!i&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function Wx(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Mr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=Gx(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=ze(c.parent),u=l?i.get(s.get(l.toLowerCase())??l):void 0;if(u&&Mr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(qx(c,u,i,s,n))),t){let _=Kx(c,o,n,r);_.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(_)].sort((h,f)=>h.localeCompare(f))})}}return a}function zx(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function xs(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function zc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function Bx(e,t,n,r,i){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=xs("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=xs("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=xs("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=xs("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=zc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=zc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),_=zc("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...s,...o?[o]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],..._?[_]:[]]}function $y(e){let t=xt(e);return t.length>yx||t.split(/[\\/]/).some(n=>n.length>wx)}async function Hx(e,t){let n=Re.isAbsolute(t)?t:Re.resolve(e,t);if($y(n))return!1;try{let r=await Qc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return Cx(r,["ENOENT","ENOTDIR"])}}async function Vx(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(s=>({item:i,artifact:s,link_kind:"files"})),...(i.docs??[]).map(s=>({item:i,artifact:s,link_kind:"docs"}))]);for(let{item:i,artifact:s,link_kind:o}of r){if(s.scope!=="project")continue;if(Tr(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=xt(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await Hx(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:o})))}return n}function Yx(e,t,n,r,i,s){let o=r==="tracked-all-strict",a=o&&!i,c=i||o,d=c?[]:Ax(t,n),l=d.length===0?[]:e.candidateFiles.filter(h=>ly(h,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(h=>!ly(h,d)),_={};if(l.length>0){let h=zt(l,s);_.pm_internals={count:l.length,paths:h.values,paths_truncated:h.truncated,paths_total:h.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:_}}function Fy(e,t,n,r,i,s,o,a="pm"){let c=Wx(e,t,i,s);zx(c);let d=Ly(c.activeItems,a),l=qc(e,i),u=ms(i,e,o?Number.POSITIVE_INFINITY:Be),_=[...Bx(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...ps(u)],h=o?Number.POSITIVE_INFINITY:Be,f=te(c.closureLikeRows.map(T=>`${T.id}:${T.fields.join(",")}`),h),g=te(c.terminalParentRows.map(T=>`${T.id}:${T.parent_id}:${T.parent_status}`),h),y=te(c.staleBlockerRows.map(T=>`${T.id}:${T.status}:${T.reasons.join(",")}`),h),w=te(d.cycle_item_ids,h),b=te(d.cycle_sample_paths,h),k=te(l.cycle_item_ids,h),C=te(l.cycle_sample_paths,h),S=te(l.cardinality_violation_rows,h),A=te(l.parent_divergence_rows,h),v=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:v?"error":_.length===0?"ok":"warn",ok:!v&&_.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:b.values,dependency_cycle_sample_paths_truncated:b.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:C.values,parent_cycle_sample_paths_truncated:C.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:S.values,hierarchy_cardinality_violation_rows_truncated:S.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:_,terminalParentFixRows:c.terminalParentFixRows}}async function Uy(e,t,n,r,i,s,o=q(Ot.schema)){let a=await Vx(e,t),c=new Map(e.map(E=>[E.id,E])),d=[...new Set(a.missingLinkedPaths)].sort((E,$)=>E.localeCompare($)),l=await xx(t,r),u=Yx(l,n,t,r,i,s),_=u.candidateFiles.filter(E=>!a.linkedProjectPaths.has(E)),h=My(_,e),f=oy(d,u.candidateFiles),g=new Map(f.map(E=>[E.path,E.classification])),y=f.filter(E=>E.classification==="moved").length,w=a.staleLinkRows.map(E=>({...E,classification:g.get(E.path)??"deleted"})).sort((E,$)=>E.item_id.localeCompare($.item_id)||E.path.localeCompare($.path)||E.link_kind.localeCompare($.link_kind)),b=[];u.strictModeForcesPmInternals&&b.push("validate_files_tracked_all_strict_forces_pm_internals"),_.length>0&&b.push(`validate_files_orphaned_paths:${_.length}`);let k=[...a.remoteLinkedPaths].sort((E,$)=>E.localeCompare($)),C=zt(k,s),S=zt(d,s),A=zt(_,s),v=zt(h.map(E=>`${E.path}:${E.classification}:owner_candidate=${E.owner_candidate?.id??"unowned"}`),s),T=s?h:zt(Py(h),!1).values,L=zt(ay(f),s),N=Ng(w,f,E=>c.get(E),o,s?1/0:Yc);return N.active_missing_linked_paths_count>0&&b.push(`validate_files_missing_linked_paths:${N.active_missing_linked_paths_count}`),{check:{name:"files",status:b.length===0?"ok":"warn",ok:b.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:Yc,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:k.length,remote_linked_paths_total:C.total,remote_linked_paths:C.values,remote_linked_paths_truncated:C.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:f.filter(E=>E.classification==="deleted").length,missing_linked_paths_malformed_count:f.filter(E=>E.classification==="malformed").length,missing_linked_path_classifications:L.values,missing_linked_path_classifications_truncated:L.truncated,...N,orphaned_paths_count:_.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:v.values,orphaned_path_classifications_truncated:v.truncated,orphaned_path_rows_count:h.length,orphaned_path_rows:T}},warnings:b,staleLinkPruneRows:w}}function Xx(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},s)=>{let o=t[s];if(o.trusted)return;let a=Wc(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${a}`)}),n}async function jy(e,t,n,r){let i=new Set(e.map(S=>S.id.toLowerCase())),s=0,o=0,a=new Set,c=[],d=e.flatMap(S=>(S.tests??[]).map(A=>({item:S,linkedTest:A}))),l=await Lr(Dr()),u=await Bg(r,d.map(({linkedTest:S})=>S),l),_=Xx(d,u);for(let{item:S,linkedTest:A}of d){if(typeof A.command!="string"||A.command.trim().length===0)continue;s+=1;let v=Ic(A.command,t);if(v.length!==0){o+=v.length;for(let T of v)a.add(T),i.has(T.toLowerCase())||c.push(`${S.id}:${T}:${Wc(A.command)}`)}}let h=[...new Set(c)].sort((S,A)=>S.localeCompare(A)),f=[...new Set(h.map(S=>S.split(":")[1]??""))].filter(S=>S.length>0).sort((S,A)=>S.localeCompare(A)),g=[];h.length>0&&g.push(`validate_command_references_stale_pm_ids:${h.length}`),_.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${_.length}`);let y=n?Number.POSITIVE_INFINITY:Be,w=te(h,y),b=te(f,y),k=te([...a].sort((S,A)=>S.localeCompare(A)),y),C=te(_,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:_.length,untrusted_linked_tests:C.values,untrusted_linked_tests_truncated:C.truncated,stale_pm_id_references_count:h.length,stale_pm_ids_count:f.length,stale_pm_ids:b.values,stale_pm_ids_truncated:b.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:g}}function Jx(e,t){let n=xi(e.map(c=>({ref:c.id,version:Ai(c)})),er,Ci),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:Be,s=te(n.outdated,i),o=te(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:er,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var Jc="pm validate auto-fix";async function Gy(e,t,n){switch(e.kind){case"set_closed_at":await Og(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Jc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new p("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Bc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function qy(e,t,n){let r=[],i=[],s=new Map;for(let o of e.filter(a=>Bc(a)===null))try{await Gy(o,t,n),r.push(o)}catch(a){i.push({fix:o,error:a})}for(let o of e.filter(a=>Bc(a)!==null)){let a=Bc(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Ph(a.item_id,{remove:c,message:Jc},t):await Eh(a.item_id,{remove:c,message:Jc},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return Um(i.map(o=>o.error)),{applied:r,failed:i}}var w2={applyValidateFix:Gy,applyValidateFixes:qy,attachValidateFixHints:vy,buildCommandReferencesCheck:jy,buildDependencyReferencesCheck:Ry,buildCloseReasonBackfillRows:Ty,buildFilesCheck:Uy,buildLifecycleCheck:Fy,buildLifecycleDependencyGraph:xy,buildLifecycleParentGraph:Gc,buildEstimateBackfillRows:Cy,buildMetadataCounts:Ey,buildMissingFieldOccurrences:Sy,buildOrphanedPathRows:My,classifyOrphanedPath:Dy,collectDefaultProjectFileCandidates:Xc,collectTrackedGitFileCandidates:wy,detectLifecycleDependencyCycles:Ly,detectLifecycleParentCycles:qc,escapeRegExp:Ay,extractItemIds:Iy,findLifecycleDependencyCycleComponents:Oy,isMetadataFieldMissing:hy,linkedArtifactPathExceedsFilesystemLimits:$y,listFilesRecursive:Zc,resolveDependencyCycleSeverity:_y,resolveParentCycleSeverity:fy,resolveFileScanMode:gy,resolveLifecycleDependencyCycleSamplePath:Cs,resolveRequestedChecks:by,resolveValidateMetadataProfile:py,resolveWorkspaceRoot:yy,sharedDirectoryPrefixLength:Ny,summarizeOrphanedPathRows:Py,summarizeDuplicateIssueCodes:ky,toMeaningfulString:ze};function Qx(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function Zx(e,t,n,r){let i=await Pg(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:kt(M())}),s=[];i.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=s.length,a=await _s(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await wn(e,yn(r));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Tt(e),l=d===null?null:await vn(d);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await bn(d??e,{includeLossless:!0,pmRoot:e}),_=u.receipts,{pendingDecisions:h,lossless:f}=kn(_);h.length>0&&s.push(`validate_merge_decisions_unreviewed:${h.length}`),Qx(s,u.invalid_evidence_count);let g=o>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:h.length,pending_merge_decision_items:[...new Set(h.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:f.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(f.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}function tt(e,t,n){n&&vy(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function eR(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await W_(e.pmRoot,e.items,r?1/0:Be,e.sourceIncomplete);tt(t,i,n)}if(e.requestedChecks.has("metadata")){let i=Px(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let s=await Ig(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:Be);t.closureTimestampFixes=s.fixes,Object.assign(i.check.details,s.details),i.warnings.push(...s.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",tt(t,i,n)}if(e.requestedChecks.has("resolution")){let i=$x(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,tt(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=Fy(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,tt(t,i,n),tt(t,Ry(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await Uy(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,tt(t,i,n)}return e.requestedChecks.has("command_references")&&tt(t,await jy(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&tt(t,await Ts(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&tt(t,Jx(e.items,r),n),e.requestedChecks.has("storage_integrity")&&tt(t,await Zx(e.pmRoot,e.items,P(e.settings,M()).type_to_folder,e.settings),n),t}function tR(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Xg(t.closeReasonBackfillRows)),r.push(...Yg(t.resolutionBackfillRows)),r.push(...Jg(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Qg(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Zg(t.staleLinkPruneRows)),r}async function nR(e,t,n,r,i,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=tR(e,t,n),{applicable:a,gated:c}=ty(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let _=await qy(a,i,s);l.push(..._.applied.map(Nr)),u.push(..._.failed.map(({fix:h,error:f})=>({...Nr(h),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((_,h)=>_.localeCompare(h)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(Nr),applied_fixes:l,gated_fixes:c.map(_=>({...Nr(_),gate_hint:`Withheld: re-run with --fix-scope ${_.gate} to apply.`})),failed_fixes:u}}async function Ky(e,t,n={}){zu(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new p("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new p("--fix-scope requires --auto-fix.",m.USAGE);let i=ey(e.fixScope),s=R(process.cwd(),t.path);await F(s);let o=await x(s),a=q(o.schema),c=P(o,M()),d=by(e),l=[],u=await Ss({includeBody:["history_drift","metadata","completeness"].some(L=>d.has(L)),pmRoot:s,settings:o,typeToFolder:c.type_to_folder,warnings:l}),_=l.length>0;if(d.has("history_drift")){let L=await Sr(s);L.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${L.actionable_unknown_event_count}`)}let h=typeof e.metadataProfile=="string"?"option":"settings",f=py(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),g=Sx(f,h,o.validation.metadata_required_fields),y=kx(o),w=_y(e.dependencyCycleSeverity),b=fy(e.parentCycleSeverity),k=gy(e.scanMode),C=yy(s),S=await eR({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:C,settings:o,items:u,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:b,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:_}),A=r?await nR(e,S,o,i,t,n):void 0,v=[...new Set(S.warnings)].sort((L,N)=>L.localeCompare(N)),T={ok:!S.checks.some(L=>L.status==="error"),has_warnings:v.length>0,checks:S.checks,warnings:v,...A!==void 0?{fixes:A}:{},generated_at:I(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?T:{...bx(T),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as rR}from"node:child_process";import{promisify as iR}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]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var sR=iR(rR),oR=16,aR=3e4;function cR(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(r=>typeof r=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function dR(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let s of Object.entries(i).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,o]of Object.entries(r)){let a=i[s];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(o===null||typeof o!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${a.type}`)}return{...r}}async function lR(e,t,n,r){let i=dR(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...yu(n)}));s.catch(()=>{});let o;try{let a=await Promise.race([s,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??aR),o.unref?.()})]);return cR(e,t.key,a)}finally{clearTimeout(o)}}function zy(e,t,n,r){let i=e;for(let s of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new et(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[s]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(s=>typeof s=="string"))return i;throw new et(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Wy(e,t,n,r){let i=e.checks.find(s=>s.name===t);if(!i)throw new et(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:zy(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function uR(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await sR("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function mR(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(oR,t.length)},async()=>{for(;r<t.length;){let s=r;r+=1;let o=t[s],a=await dt(ot(e,o.id),o.id);n[s]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function Pr(e,t={}){let n=await x(e),r=P(n),i=q(n.schema),s=(t.strict_read===!0?(await U_(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await lt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(_=>({..._,id:_.id,status:_.status,type:_.type})),o={path:e},a=M(),c=Object.fromEntries((a?.assurance_providers??[]).map(_=>[_.definition.id,{cost_class:_.runtime_definition.cost_class,network:_.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await uR(e,t.tree_id),items:s,history:t.include_history===!1?[]:await mR(e,s),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async _=>{if(_.kind==="graph"){let g=ne({operation:_.operation,parameters:_.parameters??{}}),y=d.get(g);y===void 0&&(y=X_(_.operation,void 0,void 0,{..._.parameters,full:!0},o),d.set(g,y));let w=await y;return{value:zy(w,_.field,_.kind),population_size:s.length,cost:s.length}}if(_.kind==="validate"){l??=Ky({counts:!0},o);let g=await l;return Wy(g,_.check,_.field,_.kind)}if(_.kind==="health"){u??=Ag(o,{checkOnly:!0,full:!0});let g=await u;return Wy(g,_.check,_.field,_.kind)}let h=t.providers?.[_.provider];if(h)return h(_);let f=Tu(a,_.provider);if(!f)throw new TypeError(`assurance provider ${_.provider} is not registered`);return lR(f.runtime_definition,_,e,t.trigger??"sdk")}}}import{createHash as pR}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]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function By(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=Ki({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function _R(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function fR(e,t,n,r,i,s){let o=Object.fromEntries(Aa.map(h=>[h,0])),a=0,c=0,d=0,l=0,u=[],_=pR("sha256").update(i);for(let h of r){let f=e.membership.get(h),g=n.has(h),y=f.family_ids.length>0;y&&g&&(a+=1),y||(c+=1),g||(d+=1);let w=t.get(h)?.escape_class;w!==void 0&&Aa.includes(w)&&(o[w]+=1,l+=1),_.update(ne([h,g,t.get(h)??null,f.id,f.family_ids])),(!s||!y||!g)&&u.push(h)}return{classCounts:o,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:_.digest("hex")}}function Hy(e,t,n={}){x_(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,s=new Map;for(let C of t){if(i.has(C.id))throw new TypeError(`Duplicate recurrence item ${C.id}`);i.add(C.id);let S=qi(C);S!==void 0&&s.set(C.id,S)}let o=S_(e.families,s),a=[...o.membership.keys()].sort(),c=ne({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:_,classifiedCount:h,selected:f,fingerprint:g}=fR(o,s,i,a,c,n.uncoveredOnly===!0),y=_R(n.cursor,g);if(y>f.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=f.slice(y,y+r).map(C=>{let S=o.membership.get(C),A=i.has(C);return{item_id:C,lineage_id:S.id,lineage_item_count:S.item_ids.length,family_ids:S.family_ids,present:A,...A?S.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),b=y+w.length,k=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&_===0,fingerprint:g,items:w,total:f.length,has_more:b<f.length,...b<f.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:g,offset:b})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:_,classified_item_count:h,unclassified_item_count:a.length-h,class_counts:d,escape_rate:h===a.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as hR}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]="c8cf307d-334c-5b70-93c7-991ff702e4ca")}catch{}})();var ed,Vy=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],td=["measurement","assertion","gate"];function gR(e){if(Vy.includes(e))return e;throw vi({command_path:"assurance",token:e,allowed:Vy,display_name:"assurance action"})}function Nn(e,t,n){throw new p(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function yR(e){if(!e)return Nn("kind",`Assurance declaration kind is required. Expected: ${td.join(", ")}`,"pm assurance list measurement");if(td.includes(e))return e;throw new p(`Assurance declaration kind is required. Expected: ${td.join(", ")}`,m.USAGE)}function Yy(e){if(!e)return Nn("preset",`Assurance preset is required. Expected: ${Ar.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Ar.includes(e))return e;throw new p(`Assurance preset is required. Expected: ${Ar.join(", ")}`,m.USAGE)}function nd(e){return e.owner?.trim()?e.owner.trim():Nn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function wR(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new p("assurance definition must be valid JSON",m.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new p("assurance put requires a JSON object definition",m.USAGE);return n}async function vR(e){let[t,n,r]=await Promise.all([yr(e,"measurement"),yr(e,"assertion"),yr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Xy(e,t){return t===!0?{id:e.id}:e}async function bR(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Pr(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),s=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!s.has(i.status))throw new p(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[i.id]}async function kR(e,t){let n=Ra(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>Tn))throw new p(`assurance verdict limit must be an integer from 1 through ${Tn}`,m.USAGE);let r=await jf(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Jy(e,t,n){try{return await ja(()=>$f(e,t,n))}catch(r){if(!(r instanceof p)||r.context.reason!=="assurance_evaluation_refused")throw r;let i=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],s=W(i);throw Object.assign(r.context,{changed:!1,value:n,required:`Choose a configured ${t} declaration ID using the bounded discovery command.`,why:`The requested ${t} declaration does not exist. The registry and history were not changed.`,examples:[s],recovery:{next_best_command:s,suggested_retry:s,suggested_retry_args:i}}),r}}async function ER(e,t,n){if(e==="presets"){if(t.preset??t.id)return ls(Yy(t.preset??t.id),nd(t));let i=Ar.map(s=>{let o=ls(s,"pm-owner");return{id:s,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Sn(()=>jh(n,Yy(t.preset??t.id),nd(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await Gh(await Pr(n,{resolve_tree:!1,trigger:"derive"}),nd(t)),s=t.apply?await Sn(()=>qh(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...s?{applied:s}:{}}}if(!t.id)return Nn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new p("assurance promote requires --enforcement warn|block",m.USAGE);let r=await Jy(n,"assertion",t.id);return Sn(()=>Kh(n,r,t.enforcement,{author:t.author,message:t.message}))}async function SR(e,t,n){if(!e.id)return Nn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new p("assurance run requires a trigger",m.USAGE);if(!ut.includes(e.trigger))throw new p(`Unknown assurance trigger ${e.trigger}. Expected: ${ut.join(", ")}`,m.USAGE);let i=e.trigger,[s,o]=await Promise.all([vR(t),Pr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await ja(()=>Mf(r,s,o,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await Uf(t,a,{author:e.author,message:e.message}),a}function Qy(e){throw e instanceof p?e:new p(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function TR(e){if(e.limit!==void 0)throw new p(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new p(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?By(t):Ki(t)}catch(n){if(e.action==="risk"&&n instanceof A_)throw new p(n.message,m.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Qy(n)}}function CR(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function AR(e,t,n){let r=ne(t.policy),i=ed?.pm_root===e?ed:void 0,s=new Map(n.map(d=>[d.id,hR("sha256").update(ne([E_(d),qi(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,a=o?CR(o,s):new Set,c=T_(t.policy,o?n.filter(d=>a.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...a]}:{});return ed={pm_root:e,policy_serialized:r,item_fingerprints:s,index:c},c}async function xR(e,t){let n=TR(e),r=await Pr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?C_(AR(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Hy(n.policy,r.items,n)}catch(i){return Qy(i)}}async function RR(e,t={},n={}){let r=gR(e.action),i=R(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return ER(r,e,i);if(r==="verdicts")return kR(e,i);if(r==="run")return SR(e,i,n);if(["risk","lineages"].includes(r))return xR(e,i);let s=yR(e.kind);if(r==="list")return yr(i,s);if(!e.id)return Nn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${s} <id>`);let o=e.id;if(r==="show")return Jy(i,s,o);if(r==="remove"){let l=await Sn(()=>Ff(i,s,o,{author:e.author,message:e.message}));return Xy(l,e.idOnly)}let a=wR(s,e.definition);if(a.id!==o)throw new p(`Assurance definition id ${a.id} does not match requested id ${o}`,m.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await bR(i,a)}:{}},d=await Sn(()=>Zi(i,s,a,c));return Xy(d,e.idOnly)}function nW(e,t,n){let r={...e,...t};return RR({action:ee(r,"subcommand")??ee(r,"assuranceAction")??ee(r,"operation")??"",kind:ee(r,"kind"),id:ee(r,"id"),definition:r.definition,trigger:ee(r,"trigger"),tree:ee(r,"treeId")??ee(r,"tree"),gate:ee(r,"gate"),limit:Ra(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:ee(r,"author"),message:ee(r,"message"),preset:ee(r,"preset"),owner:ee(r,"owner"),apply:r.apply===!0,enforcement:ee(r,"enforcement")},n)}import rd from"node:fs/promises";import Zy 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]="ff5e2370-3b70-5f71-9492-72906f642c85")}catch{}})();var IR=1440*60*1e3,OR=new Set(["committed","compensated"]);function LR(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:n.abandonment!==void 0?"abandoned":typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function DR(e,t,n,r,i){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-s;return OR.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function NR(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],s=LR(await rd.readFile(e,"utf8")),o=DR(t,s.status,s.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await rd.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function ew(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*IR,o=Zy.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await rd.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(j(d))return a;throw d}for(let d of c){let l=Zy.join(o,d),u=`transactions/sdk/${d}`,_=await NR(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:s});a.warnings.push(..._.warnings),a.scanned+=1;let{decision:h}=_;if(!h.remove){a.retained.push(u),a.entries.push(h.entry);continue}a.removed.push(u),a.entries.push(h.entry)}return a}import Mn from"node:fs/promises";import Ds from"node:path";import Ls from"node:fs/promises";import id 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]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var MR=864e5;function PR(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function $R(e,t){let n;try{n=await Ls.readdir(e,{withFileTypes:!0})}catch(i){if(j(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let s=id.join(e,i.name),o;try{o=await Ls.readdir(s)}catch(a){j(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of o)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function tw(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*MR,o=id.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await $R(o,a.warnings);for(let d of c){let l=id.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let _;try{_=await Ls.readFile(l,"utf8")}catch(w){if(j(w)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=PR(_),f=h===null?Number.NaN:Date.parse(h);if(!Number.isFinite(f)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:h,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=i-f,y={file:u,created_at:h,age_seconds:Math.floor(g/1e3),stale:g>s,reason:g>s?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await Ls.unlink(l)}catch(w){if(!j(w)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var $r=["index","embeddings","runtime","locks","checkpoints","transactions"],FR=1440*60*1e3,UR=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function jR(e,t,n){let r=t.relativePath,i=Ds.join(e,r),s=await Ue({path:i,scope:"project"});try{let o=await Mn.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...s,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await Mn.unlink(i):await Mn.rm(i,{recursive:!0,force:!0});let a=await ct({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...a]}}catch(o){if(j(o))return{removed:!1,warnings:s};throw o}}async function GR(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],s=[],o=Date.now()-FR;for(let a of n){let c=Ds.join(e,a.relativePath);if(!await re(c))continue;let d=(await Mn.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=Ds.posix.join(a.relativePath,l),_=Ds.join(c,l);s.push(...await Ue({path:_,scope:"project"}));let h=await Mn.stat(_).catch(f=>{if(!j(f))throw f});if(h){if(h.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await Mn.rm(_,{recursive:!0,force:!0}),s.push(...await ct({path:_,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:s}}function qR(e){if(!e||e.length===0)return[...$r];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new p(`--scope requires at least one value (${$r.join(",")})`,m.USAGE);let n=new Set;for(let r of t){if(!$r.includes(r))throw new p(`Invalid --scope value "${r}". Expected one or more of: ${$r.join(", ")}`,m.USAGE);n.add(r)}return $r.filter(r=>n.has(r))}function KR(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function TW(e,t={}){let n=R(process.cwd(),e.path);await F(n);let r=await x(n),i=t.dryRun===!0,s=qR(t.scope),o=UR.filter(f=>s.includes(f.scope)),a=[],c=[],d=[];for(let f of o){let g=await jR(n,f,i);g.removed?a.push(f.relativePath):c.push(f.relativePath),d.push(...g.warnings)}if(s.includes("runtime")){let f=await GR(n,i);a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(s.includes("locks")){let f=await cg(n,{dryRun:i,hooks:{onRead:g=>Ue({path:g,scope:"project"}),onWrite:g=>ct({path:g,scope:"project",op:"gc:lock_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(s.includes("transactions")){let f=r.checkpoints.retention_days,g=await ew(n,{dryRun:i,retentionDays:f,hooks:{onRead:y=>Ue({path:y,scope:"project"}),onWrite:y=>ct({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),u={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:f}}let _;if(s.includes("checkpoints")){let f=r.checkpoints.retention_days,g=await tw(n,{dryRun:i,retentionDays:f,hooks:{onRead:y=>Ue({path:y,scope:"project"}),onWrite:y=>ct({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...g.removed),c.push(...g.retained),d.push(...g.warnings),_={scanned:g.scanned,removed:g.removed.length,retained:g.retained.length,retention_days:f}}d.push(...await Eu({mode:i?"gc:dry-run":"gc",total_items:o.length}));let h=KR({dryRun:i,scopes:s,removed:a});return{ok:d.length===0,dry_run:i,scope:s,removed:a,retained:c,warnings:d,...l?{locks:l}:{},..._?{checkpoints:_}:{},...u?{transactions:u}:{},guidance:h,generated_at: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]="1430dcf8-9363-556d-aa33-184cea5421f9")}catch{}})();var RW=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function WR(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 Ns(e,t){return sd(e,t,{operation:"close"})}function sd(e,t,n){let r=WR(e);if(!t||r.closeReason!==void 0)return r;let i=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 p("Close reason text is required because governance.require_close_reason is enabled",m.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:i,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 nw(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,i=e.dependencies??[],s=i.filter(d=>d.kind==="blocked_by"),o=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),o&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=new Set(s),l=i.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...s.length>0?[`closed_removed_predecessors:${e.id}:${s.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${s.length}`]:[]]};let c=[...new Set([...n?[n]:[],...s.map(d=>d.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]="0912c0d0-66d6-5e13-b663-91844378a79a")}catch{}})();var zR=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function BR(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 p(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function rw(e){let t=[];for(let n of zR){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function iw(e,t,n={}){let r=rw(e);if(r.length===0)return;let i={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=r.map(a=>`--${a.key.replaceAll("_","-")}`),o=[...t,"update",e.id,...r.flatMap((a,c)=>[s[c],i[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:W(o),suggested_retry_args:o}}async function HR(e,t,n){let r=new Set,i=t;for(;typeof i=="string"&&i.trim().length>0;){let s=i.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),i=(await e(s))?.duplicate_of}return!1}function VR(e){return typeof e!="string"||e.trim().length===0}async function YR(e,t,n,r){let i=n?.trim();if(!i)return;if(i===r)throw new p("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=P(t,M()),o=new Map,a=async d=>{if(o.has(d))return o.get(d)??null;let l=await V(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return o.set(d,null),null;let{document:u}=await ue(l,{schema:t.schema});return o.set(d,u.metadata),u.metadata},c=await a(i);if(!c)throw new p(`Duplicate target "${i}" was not found. Create or locate the canonical item first.`,m.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 ${i}" --duplicate-of ${i}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await HR(a,c.duplicate_of,r))throw new p(`Circular duplicate reference detected. Target "${i}" points back to "${r}".`,m.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 p(`Duplicate target "${i}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.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 XR(e,t,n){return e.filter(r=>r.parent===t&&!fe(r.status,n)).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}function JR(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),i=Pm(e),s=t.trim().toLowerCase(),o=n.blocked_statuses;return e.filter(a=>o.has(a.status)).map(a=>({item:a,blockerIds:i.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let d=r.get(c);return d!==void 0&&fe(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function QR(e,t,n,r,i,s){let o=JR(n,r,s),a=[],c=[],d;for(let l of o)try{let u=await me({pmRoot:e,settings:t,id:l.id,op:"update",author:i,message:`Auto-unblocked after blocker ${r} closed`,mutate(_){let h=_.metadata.dependencies??[],f=h.filter(y=>{let w=y.id.trim().toLowerCase();return y.kind!=="blocked_by"||!l.blocker_ids.includes(w)});_.metadata.status=s.open_status,delete _.metadata.blocked_by,delete _.metadata.blocked_reason,_.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${l.blocker_ids.join(", ")}).`,f.length>0?_.metadata.dependencies=f:delete _.metadata.dependencies;let g=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==h.length&&g.push("dependencies"),{changedFields:g}}});a.push(`auto_unblocked:${u.item.id}:resolved_blockers=${l.blocker_ids.join(",")}`),c.push(u.item.id)}catch(u){d===void 0&&Ut(u)&&(d=u);let _=u instanceof Error?u.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${l.id}:${_}`)}if(d!==void 0)throw new p(`${r} was closed, but auto-unblocking ${String(d.context.item_id)} was refused. ${d.message}`,d.exitCode,{...d.context,side_effects:[{path:`history/${r}.jsonl`,op:"close"},...c.map(l=>({path:`history/${l}.jsonl`,op:"update"}))]});return a}async function GW(e,t,n){if(!Ut(e)||!e.context.side_effects?.some(i=>`${i.op}:${i.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(i=>i.op==="update").map(i=>i.path.slice(8,-6)).map(i=>`auto_unblocked:${i}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:yi(e),...await Fm(e,n)}}}function ZR(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:i,key:s}of r){if(typeof i!="string")continue;let o=i.trim();o.length!==0&&(e[s]=o,n.push(s))}return n}function eI(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:i,value:s}of r)VR(e[i])&&(e[i]=s,n.push(i));return n}function tI(e,t,n,r){let i=[];if(t!=="off"){let s=rw(e);if(s.length>0){let o=s.map(a=>a.label);if(t==="strict"){let a=s.map(d=>`--${d.key.replaceAll("_","-")}`),c=[...r,"update",e.id,...a.flatMap(d=>[d,"<value>"])];throw new p(`Cannot close item ${e.id}: missing ${o.join(", ")}. Populate fields or use --validate-close warn.`,m.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:W(c),suggested_retry_args: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."]})}i.push(`close_validation_missing_fields:${e.id}:${o.join(",")}`)}if(n.length>0){if(t==="strict")throw new p(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);i.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return i}return n.length>0&&i.push(`closed_with_active_children:${e.id}:${n.join(",")}`),i}function nI(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function rI(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function iI(e,t){if(fe(e.status,t.statusRegistry)&&!t.force)throw new p(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:iw(e,t.commandScope,t.options)});let n=ZR(e,t.options),r=eI(e,t.duplicateOf),i=tI(e,t.validateCloseMode,t.activeChildIds,t.commandScope);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let o=["status","closed_at",...s?["completed_at"]:[],...nI(e,t.closeReason),...n];if(Om(e)&&(e.plan_mode="completed",o.push("plan_mode")),t.duplicateOf!==void 0){o.push("duplicate_of");for(let c of r)o.includes(c)||o.push(c)}o.push(...rI(e));let a=nw(e,t.lifecyclePolicy);return o.push(...a.changedFields),i.push(...a.warnings),{changedFields:o,...i.length>0?{warnings:i}:{}}}async function sI(e,t,n,r){let i=R(process.cwd(),r.path),s=dn(r);await F(i);let o=await x(i),a=q(o.schema),c=U(n.author,o.author_default),d=P(o,M()).type_to_folder,l=await V(i,e,o.id_prefix,o.item_format,d);if(!l)throw await $t(i,e,o.id_prefix,d);let u=await YR(i,o,n.duplicateOf,l.id),_={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},h=Ns({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},_.requireCloseReason).closeReason,f=BR(n.validateClose)??o.governance.close_validation_default,g=await Ee(i,o.item_format,d,void 0,o.schema),y=XR(g,l.id,a),w=I(),b=n.completedAt===void 0?w:le(n.completedAt,new Date(w),"completed-at"),k={timestamp:b,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${W([...s,"update",l.id,"--completed-at","<ISO>"])}.`}:{}},C=await hn({pmRoot:i,settings:o,id:l.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(A){return n.completedAt===void 0&&A.metadata.completed_at!==void 0&&(k={timestamp:A.metadata.completed_at,source:"existing"}),iI(A.metadata,{pmRoot:i,commandScope:s,statusRegistry:a,force:n.force,options:n,duplicateOf:u,validateCloseMode:f,activeChildIds:y,closeReason:h,closedAt:w,completedAt:b,lifecyclePolicy:_})}}),S=f==="warn"?iw(C.item,s):void 0;return{item:C.item,changed_fields:C.changedFields,...S?{follow_up:{kind:"complete_close_evidence",missing:S.missing,suggested_command:S.suggested_retry,suggested_command_args:S.suggested_retry_args}}:{},warnings:[...C.warnings,...await QR(i,o,g,l.id,c,a)],completion:k}}function Ms(e,t,n,r){return sI(e,t,n,r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function sw(e){return[...e].sort().join("\0")}function oI(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let i=e.predecessors.get(n);i?i.push(t):e.predecessors.set(n,[t])}function ow(e,t,n,r,i){let s=t.resolve(i);if(s?.ordering!==!0)return;let o=P_(r),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";oI(e,c?n:a,c?a:n)}function aI(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0);for(let i of r){let s=i.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let i of r){let s=i.id.trim();ow(n,t,s,i.blocked_by,"blocked_by");for(let o of i.dependencies??[])typeof o!="object"||o===null||ow(n,t,s,o.id,typeof o.kind=="string"?o.kind:"related")}for(let i of[n.successors,n.predecessors])for(let s of i.values())s.sort();return n}function cI(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();for(let s of[e.successors,e.predecessors])for(let o of s.get(i)??[])n.has(o)||(n.add(o),r.push(o))}return n}function dI(e,t){let n=new Map;for(let r of t){let i=(e.successors.get(r)??[]).filter(s=>t.has(s));i.length>0&&n.set(r,i)}return n}function aw(e,t,n){let r=aI(e,t),i=r.canonicalIds.get(n.trim().toLowerCase());if(i===void 0)return{cycles:[],successors:new Map,canonical:n};let s=dI(r,cI(r,i));return{cycles:V_(s).filter(o=>o.includes(i)),successors:s,canonical:i}}function lI(e,t,n){let r=new Set(t),i=r.has(n)?n:t[0];if(e.get(i)?.includes(i))return[i,i];for(let s of e.get(i)??[]){if(!r.has(s))continue;let o=uI(e,r,i,s);if(o)return o}return[...t,t[0]]}function uI(e,t,n,r){let i=[[r]],s=new Set([n,r]);for(;i.length>0;){let o=i.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||s.has(c)||(s.add(c),i.push([...o,c]))}}}function Ps(e,t,n){let r=oe(),i=aw(e,r,n),s=aw(t,r,n),o=new Set(i.cycles.map(sw)),a=new Set(Ia(e,void 0,r).map(c=>`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`));return[...Ia(t,void 0,r).filter(c=>c.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`)).map(c=>`ordering_storage_contradiction_created:${Y_(c)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(c=>!o.has(sw(c))).map(c=>`ordering_cycle_created:${lI(s.successors,c,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function $s(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function cw(e,t,n,r,i){let s=JSON.stringify([t,n,r]),o=e.get(s);o===void 0&&(o={kind:t,direction:n,node_id:r,endpoints:new Set},e.set(s,o)),o.endpoints.add(i)}function dw(e,t){let n=new Map;for(let r of e)for(let i of r.dependencies??[]){let s=t.resolve(i.kind);s===void 0||s.hierarchy||(s.outgoing==="one"&&cw(n,s.kind,"outgoing",r.id,i.id),s.incoming==="one"&&cw(n,s.kind,"incoming",i.id,r.id))}return n}function Fs(e,t,n=oe()){let r=dw(e,n),i=dw(t,n);for(let s of[...i.keys()].sort()){let o=i.get(s);if(o.endpoints.size<=1)continue;let a=r.get(s);if(![...o.endpoints].every(c=>a?.endpoints.has(c)))throw new p(`Relationship ${o.kind} permits only one ${o.direction} endpoint for ${o.node_id}.`,m.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:o.kind,relationship_cardinality:{kind:o.kind,direction:o.direction,node_id:o.node_id,endpoint_ids:[...o.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1ce8c06c-cdc7-57bb-b4c3-477b2e07d71c")}catch{}})();var Vt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",ur,G_,"FORCE_COLOR"]),Gs=/^[A-Za-z_][A-Za-z0-9_]*$/,Ht=["schema","tracker","auto","none"],lw=["source","isolated","snapshot"];function Fr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new p(`${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`,m.USAGE);let o=i.slice(0,s).trim(),a=i.slice(s+1);if(!Gs.test(o))throw new p(`${t} env_set key "${o}" is invalid`,m.USAGE);if(Vt.has(o.toUpperCase()))throw new p(`${t} env_set key "${o}" is reserved for sandbox safety`,m.USAGE);r[o]=a}return Object.keys(r).length>0?r:void 0}function Ur(e,t){if(!e)return;let n=ha(e,{separators:/[;,\n]/});if(n.length===0)throw new p(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!Gs.test(r))throw new p(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(Vt.has(r.toUpperCase()))throw new p(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function qs(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 p(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Ks(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Ht.includes(n))return n;throw new p(`${t} pm_context_mode must be one of: ${Ht.join(", ")}`,m.USAGE)}function Yt(e,t){if(!e)return;let n=e.trim().toLowerCase();if(lw.includes(n))return n;throw new p(`${t} workspace_context_mode must be one of: ${lw.join(", ")}`,m.USAGE)}function Xt(e){if(!e)return;let t=ha(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Pn(e,t,n){let r=Xt(e);if(!(!r||r.length===0)){for(let i of r)try{new RegExp(i,"m")}catch(s){throw new p(`${t} ${n} includes invalid regex "${i}": ${s instanceof Error?s.message:String(s)}`,m.USAGE)}return r}}function Ws(e,t){if(!e)return;let n=ge(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new p(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function zs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let o=i.slice(0,s).trim(),a=i.slice(s+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[o]=a}return Object.keys(r).length>0?r:void 0}function Bs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new p(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let i of n){let s=i.indexOf("=");if(s<=0)throw new p(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let o=i.slice(0,s).trim(),a=i.slice(s+1).trim();if(o.length===0||a.length===0)throw new p(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new p(`${t} assert_json_field_gte value for "${o}" must be numeric`,m.USAGE);r[o]=c}return Object.keys(r).length>0?r:void 0}var mI=new Set(at);function Hs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pI(e,t){let n={},r=[];for(let[i,s]of Object.entries(e)){let o=i.toLowerCase();if(!mI.has(o)){r.push(i);continue}if(Object.hasOwn(n,o))throw t(`provides key "${i}" more than once after case normalization`);n[o]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${at.join(", ")}.`);return n}function Bt(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 Us(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let i=typeof r=="string"?[r]:r;if(!Array.isArray(i)||i.some(o=>typeof o!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=i.filter(o=>o.length>0);return s.length>0?s:void 0}function uw(e,t,n){let r=Us(e,t,n);if(r){for(let i of r)try{new RegExp(i,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${i}": ${s instanceof Error?s.message:String(s)}`)}return r}}function js(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 _I(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let i=n===void 0?void 0:js(n,"timeout_seconds",t),s=r===void 0?void 0:js(r,"timeout",t);if(i!==void 0&&s!==void 0&&i!==s)throw t("timeout and timeout_seconds must match when both are provided");let o=i??s;if(!Number.isInteger(o)||o<=0)throw t("timeout_seconds must be a positive integer");return o}function fI(e,t){let n=Bt(e,"scope",t);if(n===void 0)return"project";if(!Fe.includes(n))throw t(`field "scope" must be one of: ${Fe.join(", ")}`);return n}function hI(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Hs(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[i,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${i}" must be a string`);if(!Gs.test(i))throw t(`field "env_set" key "${i}" is invalid`);if(Vt.has(i.toUpperCase()))throw t(`field "env_set" key "${i}" is reserved for sandbox safety`);r[i]=s}return Object.keys(r).length>0?r:void 0}function gI(e,t){let n=Us(e,"env_clear",t);if(n){for(let r of n){if(!Gs.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Vt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function yI(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 wI(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=js(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 vI(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Hs(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[i,s]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${i}" must be a string, number, or boolean`);r[i]=String(s)}return Object.keys(r).length>0?r:void 0}function bI(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Hs(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[i,s]of Object.entries(n)){if(i.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[i]=js(s,`assert_json_field_gte.${i}`,t)}return Object.keys(r).length>0?r:void 0}function kI(e,t,n){let r=_=>new p(`${n} ${t} ${_}`,m.USAGE);if(!Hs(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${at.join(", ")}.`);let i=pI(e,r),s=Bt(i,"command",r),o=Bt(i,"cmd",r);if(s!==void 0&&o!==void 0&&s!==o)throw r("command and cmd must match when both are provided");let a=s??o;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Bt(i,"path",r),d=Bt(i,"pm_context_mode",r);if(d!==void 0&&!Ht.includes(d))throw r(`field "pm_context_mode" must be one of: ${Ht.join(", ")}`);let l=Yt(Bt(i,"workspace_context_mode",r),`${n} ${t}`),u=Bt(i,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:fI(i,r),timeout_seconds:_I(i,r),pm_context_mode:d,workspace_context_mode:l,env_set:hI(i,r),env_clear:gI(i,r),shared_host_safe:yI(i,"shared_host_safe",r),assert_stdout_contains:Us(i,"assert_stdout_contains",r),assert_stdout_regex:uw(i,"assert_stdout_regex",r),assert_stderr_contains:Us(i,"assert_stderr_contains",r),assert_stderr_regex:uw(i,"assert_stderr_regex",r),assert_stdout_min_lines:wI(i,r),assert_json_field_equals:vI(i,r),assert_json_field_gte:bI(i,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function jr(e,t){let n=e.trim();if(n.length===0)throw new p(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(s){throw new p(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let i=Array.isArray(r)?r:[r];if(i.length===0)throw new p(`${t} array must include at least one linked-test entry object`,m.USAGE);return i.map((s,o)=>kI(s,i.length>1?`entry ${o+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]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var EI={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 SI(e){return EI[e]}function ad(e){return SI(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]="b653115b-596b-5c07-b1f7-541fa1f04a33")}catch{}})();var TI="hierarchy-integrity";async function Vs(e){let t=e.required?await mn(e.pmRoot,TI,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Ys(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Xs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Js(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Bl.includes(t))return t;let n=ge(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new p("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function Qs(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new p("Regression must be one of true|false|1|0",m.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]="6ccfe6c7-3911-5623-aa29-5eff0293f816")}catch{}})();var mw=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48513c82-4195-51fc-bd68-480148a54d10")}catch{}})();var CI=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function Zs(e){let t=mw.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,i)=>i.toUpperCase()),n=[["update",Ca],["create",Ta]].flatMap(([r,i])=>i.flatMap(s=>{if(s.target!==t)return[];let o=s.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:o}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:i})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${i} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}var _w={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function pw(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function fw(e){if(e==="update_many"){let i=fw("update"),s=pw(sr("update-many"));return{options:new Set([...i.options,...s.map(o=>oa(o))]),flags:new Set([...i.flags,...s])}}let t=e==="update"?Ca:Ta,n=pw([...sr(e),...Gi]),r=[...t.flatMap(i=>[i.target,...i.keys]),...n.map(i=>oa(i)),...e==="update"?CI:[]];return{options:new Set(r),flags:new Set(n)}}function AI(e,t){let n=_w[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function xI(e,t,n,r){return e.definitions.some(i=>i.metadata_key===t.metadata_key&&i.commands.includes(n)&&Ru(r,i)!==void 0)}function eo(e,t,n){let r=_w[t],i=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([s])=>s!=="field"));return s=>{let o=Cu(s),a=e.definitions.filter(h=>h.metadata_key===o||h.key===o),c=a.find(h=>h.commands.includes(t))??a[0];if(c===void 0)return;let d=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[s]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(i!==void 0&&xI(e,c,t,i))return{recovery:{provided_fields:[s]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${s} assignment so the field receives one value.`,d]};let l=fw(t),u=xu(c,e,l,t),_=u===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${sa(u)} <value>`;return{recovery:{provided_fields:[s],...u===void 0?{}:{suggested_flags:[sa(u)]}},nextSteps:[_,AI(Au(c,e,l.options,t),t),d]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="202cbe4e-7d36-5b12-be9d-d35608a6b36d")}catch{}})();var RI=new Set(["none","null"]);function to(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 He(e){return e===void 0?!1:RI.has(e.trim().toLowerCase())}function no(e,t,n){if(!He(e))return;let r=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${r}`.trim(),m.USAGE)}function Ie(e,t,n){if(!e||e.length===0||Oe(e)||!e.some(i=>He(i)))return;let r=n?` ${n}`:"";throw new p(`${t} no longer accepts "none" or "null".${r}`.trim(),m.USAGE)}function ro(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(s=>typeof s=="string"))throw new p(`${n.valueFlag} entries must be strings.`,m.USAGE);if(Oe(r))continue;let i=r;if(i.some(s=>He(s))){if(i.filter(s=>!He(s)).length>0)throw new p(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,m.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var II=new Set(["event","meeting","reminder","milestone","decision","adr"]);function hw(e,t,n,r){if(II.has(t.trim().toLowerCase())||n!==r.open_status)return;let i=Ke("in_progress",r);if(!(i===void 0||i===r.open_status))return{command:`pm claim ${e} --start`,to_status: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]="528a6201-58cb-544b-a831-5ce3bff3bbc2")}catch{}})();var io=["close_reason","close-reason"],cd=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],dd=[{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"}],gw=[...cd,...dd],so=[{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 ld(e,t){return e.flatMap(n=>n.includes(",")&&t(n)?[n]:n.split(","))}function oo(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};let r=ld(e.raw,i=>e.resolveDefinition(i.trim().toLowerCase())!==void 0);for(let i of r){let s=i.trim().toLowerCase();if(!s)throw new p("--unset values must not be empty; name each field once, for example --unset parent,release",m.USAGE);if(He(s))throw new p('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',m.USAGE);let o=e.resolveDefinition(s);if(!o)throw new p(`Unsupported --unset field "${i}". Supported fields: ${e.supportedFields}`,m.USAGE);t.add(o.metadataKey),n.add(o.optionKey)}return{metadataKeys:t,optionKeys:n}}function ao(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let i=n.command_to_fields?.get(t)??[];for(let s of i){if(s.allow_unset===!1)continue;let o=new Set;if(typeof s.key=="string"&&s.key.length>0&&o.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&o.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(o.add(s.cli_flag.replaceAll("-","_").toLowerCase()),o.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(o.add(a.replaceAll("-","_").toLowerCase()),o.add(a.toLowerCase()));if(o.has(r))return{optionKey:s.key,metadataKey:s.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function ww(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 p(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function ud(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ve(e,t,n,r=n){if(!t.includes(e))throw new p(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var vw=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function OI(e,t){return t==="defined"?e!==void 0:!!e}function yw(e,t,n){if(!OI(e,n))return;let r=ge(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new p(`--event ${t} must be an integer >= 1`,m.USAGE);return r}function LI(e,t,n){let r=e?le(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new p("--event recur_until must be at or after start",m.USAGE);return r}function DI(e){return Array.from(new Set(ud(e).map(t=>Ve(t.toLowerCase(),Ql,"event weekday")))).sort((t,n)=>Qo(t)-Qo(n))}function NI(e){return Array.from(new Set(ud(e).map(t=>{let n=ge(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new p("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function MI(e,t){return Array.from(new Set(ud(e).map(n=>le(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function bw(e,t,n,r){let i=e.recur_freq?.trim(),s=e.recur_interval?.trim(),o=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![i,s,o,a,c,d,l].some(b=>b!==void 0))return;if(!i)throw new p("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let u=Ve(i.toLowerCase(),Jl,"event recurrence frequency"),_=yw(s,"recur_interval",r),h=yw(o,"recur_count",r),f=LI(a,t,n),g=DI(c),y=NI(d),w=MI(l,n);return{freq:u,interval:_,count:h,until:f,by_weekday:g.length>0?g:void 0,by_month_day:y.length>0?y:void 0,exdates:w.length>0?w:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();function Gr(e,t=oe()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(Jo),i=[...Jo,...t.list().filter(({kind:s})=>!r.has(s)).flatMap(({kind:s,aliases:o})=>[s,...o])];throw new p(`Invalid dependency kind value "${e}". Allowed: ${i.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:i},required:`dependency kind must be one of: ${i.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function qr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new p(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.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 Kr(e,t,n=oe()){for(let r of t??[])try{hu(e,r.id,r.kind,n)}catch(i){throw new p(yi(i),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function kw(e,t){return(await ue(e,{schema:t})).document.metadata.created_at}async function PI(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await V(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:kw(n,t.schema)}function $I(e){let t=e.registry.require(e.dependency.kind);return new p(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.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 FI(e){let t=e.dependencies.filter(i=>e.registry.resolve(i.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(i.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:i,located:s})=>s===null?[]:[[i,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:i})=>i))].map(async i=>[i,await kw(n.get(i),e.context.schema)])));for(let i of e.holders){let s=await PI(i,e.context);if(s!==void 0)for(let o of t){let a=r.get(o.id),c=Date.parse(s),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw $I({holder:i,dependency:o,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function co(e){let t=e.registry??oe(),n=(e.dependencies??[]).filter(o=>!Mm(o.source_kind)),r=[...new Set(n.map(o=>o.id))],i=await Promise.all(r.map(async o=>({target:o,located:await V(e.pmRoot,o,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=i.filter(({located:o})=>o===null).map(({target:o})=>o).sort((o,a)=>o<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new p(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,m.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:s,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 ${s.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:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await FI({dependencies:n,missingTargets:s,resolutions:i,holders:e.holders??[],registry:t,context:e}),s.map(o=>`dependency_target_unresolved:${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]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Ew="--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.",UI="--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).",jI=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,GI=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Tw=1e3,md=60*Tw,qI=60*md;function Sw(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new p(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function KI(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new p(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let i=r.replace(/^([+-]?\d+)mo$/i,"$1m"),s=jI.exec(r);if(s){let c=s[1]==="-"?-1:1,d=Number.parseInt(s[2],10)*c;return Sw(n.getTime()+d*md,r)}let o=GI.exec(r);if(o){let[,c,d,l,u]=o;if(d||l||u){let _=c==="-"?-1:1,h=Number.parseInt(d??"0",10),f=Number.parseInt(l??"0",10),g=Number.parseInt(u??"0",10),y=h*qI+f*md+g*Tw;return Sw(n.getTime()+_*y,r)}}let a=i.startsWith("+")||i.startsWith("-")?i:`+${i}`;return le(a,n,"event.duration")}function Cw(e,t,n,r){if(t&&n)throw new p(UI,m.USAGE);if(n){let s=KI(e,n);if(s<e)throw new p(Ew,m.USAGE);return s===e?void 0:s}if(!t)return;let i=le(t,r,"event.end");if(i<e)throw new p(Ew,m.USAGE);if(i!==e)return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var WI=["at","date","text","title"],zI=["start","date","end","duration","title","description","location","timezone","all_day",...vw],BI=["key","value"];function Aw(e,t){return t==="trimmed"?e?.trim():e}function HI(e,t){return t==="defined"?e!==void 0:!!e}function lo(e,t,n){return e.map(r=>{let i=Q(r,"--reminder");we(i,"--reminder",WI);let s=Aw(i.at??i.date,n.valueMode),o=Aw(i.text??i.title,n.valueMode);if(!s||!o)throw new p("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=o.trim();if(!a)throw new p("--reminder text must not be empty",m.USAGE);return{at:le(s,t,"reminder.at"),text:a}})}function uo(e,t,n){return e.map(r=>{let i=Q(r,"--event");we(i,"--event",zI);let s=(i.start??i.date)?.trim();if(!s)throw new p("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let o=le(s,t,"event.start"),a=i.end?.trim(),c=i.duration?.trim(),d=Cw(o,a,c,t),l=i.title,u=i.description,_=i.location,h=i.timezone,f=l?.trim(),g=u?.trim(),y=_?.trim(),w=h?.trim(),b=[["title",l,f],["description",u,g],["location",_,y],["timezone",h,w]];for(let[A,v,T]of b)if(v!==void 0&&!T)throw new p(`--event ${A} must not be empty`,m.USAGE);let k=i.all_day?.trim(),C=bw(i,o,t,n.recurrenceEmptyNumericGuard),S=HI(k,n.allDayEmptyGuard)?ww(k,"--event all_day"):void 0;return{start_at:o,end_at:d,title:f,description:g,location:y,all_day:S,timezone:w,recurrence:C}})}function mo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new p("--type-option values must not be empty",m.USAGE);let i,s;if(r.includes(",")||r.includes(`
|
|
10
|
+
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let o=Q(r,"--type-option");we(o,"--type-option",BI),i=o.key?.trim(),s=o.value?.trim()}else{let o=r.indexOf("="),a=r.indexOf(":"),c=o;if(o<=0&&a>0&&(c=a),c<=0||c===r.length-1)throw new p("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);i=r.slice(0,c).trim(),s=r.slice(c+1).trim()}if(!i||!s)throw new p("--type-option requires key and value",m.USAGE);t[i]=s}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]="dfc60af7-26bb-552f-a517-ae0dd5442d4f")}catch{}})();var VI=["strict","progressive"],YI=["lightweight"],Ow=new Set(["Reminder","Meeting","Event"]),XI=new Set(["author","created_at","text"]),_d=[...gw,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...so],JI=(()=>{let e=new Map;for(let t of _d)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),po=new Map(_d.map(e=>[e.optionKey,e.canonical])),QI=_d.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function ZI(e,t){let n=se(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function eO(e,t){let n=e.default_status;if(n!==void 0){let r=se(n,t);if(r)return r}return t.open_status}function pd(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var tO=to();function Lw(e){if(Oe(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s};He(t.template)&&(t.template=void 0);let r=new Set([...po.keys(),"rank"]);for(let i of r){if(Oe(e,i))continue;let s=t[i];if(typeof s!="string"||!He(s))continue;let o=i==="rank"?"order":po.get(i)??i;n(o),t[i]=void 0}return Je(e,ro(t,tO))}function be(e){if(e!==void 0)return e}function nO(e,t){return oo({raw:e,supportedFields:QI,resolveDefinition:n=>JI.get(n)??ao(n,"create",t)})}var xw=["id","kind","type","author","created_at","source_kind"],_o=["path","scope","note"];function rO(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let s=i.trim(),o=fo(s,xw);qr(s,o);let a=o?Q(i,"--dep"):{id:s,kind:"related"};o&&we(a,"--dep",xw);let c=be(a.id),d=iO(be(a.kind??a.type));if(!c||!d)throw new p("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(c.trim().toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=dr(be(a.source_kind)),u=be(a.author);return{id:lr(c,n,l),kind:Gr(d),created_at:pd(a.created_at,t),author:u??r,source_kind:l??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function iO(e){return typeof e=="string"?oe().resolve(e)?.kind??e.trim():e}function fo(e,t){return ql(e,t)?!0:sn(e)}function Qt(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ie(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(i=>{let s=i.trim(),o=()=>{if(s.length===0)throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:r,text:s}},a;try{a=Q(i,e)}catch(d){if(e==="--comment"||e==="--note"||e==="--learning")return o();throw d}if(Object.keys(a).filter(d=>!XI.has(d)).length>0)return{created_at:pd(a.created_at,n),author:be(a.author)??r,text:s};let c=a.text??"";if(c==="")throw new p(`${e} requires text=<value>`,m.USAGE);return{created_at:pd(a.created_at,n),author:be(a.author)??r,text:c}}),explicitEmpty:!1})}function fd(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=fo(n,_o);Hn(n,"--file","file path",r);let i=r?Q(t,"--file"):{path:n};if(r&&we(i,"--file",_o),!i.path)throw new p("--file requires path=<value> or a bare file path",m.USAGE);return{path:i.path,scope:Ve(i.scope??"project",Fe,"file scope"),note:be(i.note)}}),explicitEmpty:!1})}function hd(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=fo(n,at);Hn(n,"--test","test command",r);let i=r?gi(Q(t,"--test"),"--test"):{command:n},s=be(i.command),o=be(i.path);if(!s)throw new p("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let a=be(i.timeout_seconds),c=be(i.timeout);if(a&&c&&a!==c)throw new p("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let d=a??c;return{command:s,path:o,scope:Ve(i.scope??"project",Fe,"test scope"),timeout_seconds:d?ge(d,"timeout_seconds"):void 0,pm_context_mode:Ks(i.pm_context_mode,"--test"),workspace_context_mode:Yt(i.workspace_context_mode,"--test"),env_set:Fr(i.env_set,"--test"),env_clear:Ur(i.env_clear,"--test"),shared_host_safe:qs(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Xt(i.assert_stdout_contains),assert_stdout_regex:Pn(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Xt(i.assert_stderr_contains),assert_stderr_regex:Pn(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ws(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:zs(i.assert_json_field_equals,"--test"),assert_json_field_gte:Bs(i.assert_json_field_gte,"--test"),note:be(i.note)}}),explicitEmpty:!1})}function gd(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=fo(n,_o),i=r?Q(t,"--doc"):{path:n};if(r&&we(i,"--doc",_o),!i.path)throw new p("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:i.path,scope:Ve(i.scope??"project",Fe,"doc scope"),note:be(i.note)}}),explicitEmpty:!1})}function sO(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--reminder","Use --clear-reminders to clear reminders."),{values:lo(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function oO(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--event","Use --clear-events to clear linked events."),{values:uo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function aO(e,t,n,r=[]){let i=[...Cl.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(i))}function cO(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Rw(e,t,n){let r=Vn("create",e);if(!r)throw new p(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return r}function dO(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 Dw(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 lO(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Rw(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Rw(r,e.name,"required_create_repeatables"));return n}function uO(e,t,n,r){for(let i of e)if(!(!Dw(t,i)&&!n.has(i)))throw new p(`Option ${Se("create",i)} is disabled for type "${r}" by command_option_policies`,m.USAGE)}function mO(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!ad(s));if(r.length===0)return;let i=[...new Set(r.map(s=>Se("create",s)))].sort((s,o)=>s.localeCompare(o));throw new p(`Strict create mode requires concrete values for ${i.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,m.USAGE)}function pO(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ie(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:mo(e),explicitEmpty:!1})}async function _O(e){return await li(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 fO(e){return Dt(e)?await _O(e):e}function hO(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 p(`Invalid --create-mode value "${e}". Allowed: ${VI.join(", ")}`,m.USAGE)}function gO(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new p("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new p(`Invalid --schedule-preset value "${e}". Allowed: ${YI.join(", ")}`,m.USAGE)}function yO(e,t,n){let r=hO(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new p("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function wO(e,t,n,r,i){let s=e.name,o=dO(t),a=lO(e,n),c=cn(e,"create",a);if(c.errors.length>0)throw new p(c.errors.join("; "),m.CONFLICT);uO(c.disabled,o,r,s),mO(c.required,n,r);let d=u=>u==="author"&&i!=="unknown"||u==="status"&&e.default_status!==void 0||r.has(u)&&ad(u)?!0:Dw(o,u),l=c.required.filter(u=>!d(u));return[...new Set(l.map(u=>Se("create",u)))].sort((u,_)=>u.localeCompare(_))}var Nw=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function vO(e,t){let n=[];for(let r of e){let i=r.match(Nw);i&&i[2]===t&&n.push(i[1])}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function bO(e,t){return e.filter(n=>{let r=n.match(Nw);return!r||r[2]!==t})}function kO(e,t,n,r){let i=bO(e,t);if(i.length===0)return;let s=Mw(n,[],[],r.open_status);throw new p(i.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function EO(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function SO(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function Mw(e,t,n,r){let i=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],o=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of o){if(a.has(c))continue;let d=$w[c];i.push(...d?[d]:SO(c,e.name,r)),a.add(c)}for(let c of n){let d=EO(e,c);i.push("--type-option",`${c}=${d}`)}return i.join(" ")}function yd(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new p("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new p('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.',m.USAGE):new p(`Missing required option ${t}`,m.USAGE);return n}function TO(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=Array.isArray(i)?[...i]:i;for(let[r,i]of Object.entries(t))i!==void 0&&(n[r]=Array.isArray(i)?[...i]:i);return Je(t,n)}function CO(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function AO(){let e=M();return e?e.commands.some(t=>t.action==="templates-show"||CO(t.command)==="templates show"):!1}function xO(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new p(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let r={};for(let[i,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[i]=s;continue}if(Array.isArray(s)&&s.every(o=>typeof o=="string")){r[i]=[...s];continue}throw new p(`Templates package returned unsupported option value for "${i}" in template "${t}".`,m.GENERIC_FAILURE)}return r}async function RO(e,t,n){if(!AO())throw new p("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let r=await Su({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?Rm("templates show",r):new p(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,m.USAGE);return xO(r.result,e)}function X(e,t,n){return e.has(t)||n===void 0?void 0:be(n)}function Jt(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var IO=new Set(["milestone","meeting","reminder","event"]);function Pw(e,t,n,r){let i=t!==void 0,s=n!==void 0&&n.length>0,o=r!==void 0&&r.length>0;return IO.has(e.toLowerCase())&&!i&&!s&&!o}function OO(e,t,n,r,i){let s=[];return e.toLowerCase()==="event"&&(i===void 0||i.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),Pw(e,n,r,i)&&s.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)`),s}async function LO(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let i=await Ku(r);return i===void 0?{parent:e,parentSource:void 0}:{parent:i,parentSource:"focus"}}async function DO(e,t,n,r,i,s){let o=gn(Oi(i),t.id_prefix);if(ji(o))return{parent:o,warnings:[]};if(Di(r,o,t.id_prefix),await V(e,o,t.id_prefix,t.item_format,n.type_to_folder))return{parent:o,warnings:[]};let a=Ze(o,t.id_prefix);return{parent:o,warnings:Li(a,s).warnings}}async function NO(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await DO(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function MO(e){if(e.explicitId===void 0)return sm(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});or(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||om(t))throw new p("--id must not be empty or use a placeholder token",m.USAGE);let n=Ze(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new p("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function Iw(e,t,n,r,i){let s=X(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let o=Mi(r,s,i);return{value:o.value,warnings:o.warnings}}async function PO(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:i,blockedBy:s,status:o,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:o};let u=Ze(s,n.id_prefix),_=await V(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!_)return{dependencyValues:l,status:o};if((l??[]).some(f=>f.id===_.id&&f.kind==="blocked_by")||(l=[...l??[],{id:_.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:o};let h=i.blocked_statuses.has("blocked")?"blocked":[...i.blocked_statuses].sort((f,g)=>f.localeCompare(g))[0]??i.open_status;return{dependencyValues:l,status:h}}function $O(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&st(r,n)){e.type=r;return}st("Task",n)&&(e.type="Task")}function FO(e,t){return e.options.filter(n=>Vn("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 p(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function UO(e,t,n,r,i){let s=e,o=[];if(s.template!==void 0){let f=s.template.trim();if(f.length===0)throw new p("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let g=await RO(f,t,n);s=Lw(ar("create",TO(g,s)))}if(s.type===void 0&&$O(s,r,i),s.type===void 0)throw new p("Missing required option --type <value>",m.USAGE);let a=st(s.type,i);if(!a){let f=am(s.type),g=f?st(f,i):void 0;if(g)o.push(`type_coercion:${s.type.trim()}:${g}`),s.type=g,a=g;else throw new p(Pi(s.type,i.types,Ti(n,r.schema)),m.USAGE)}let c=_i(a,i);if(!c)throw new p(`Invalid type value "${s.type}"`,m.USAGE);let d=c.name,l=FO(c,s),u=l.map(f=>`${f.key}=${String(s[f.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let f of l)delete s[f.key]}let _=gO(s.schedulePreset);if(_!==void 0&&!Ow.has(d))throw new p(`--schedule-preset ${_} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let h=yO(s.createMode,_,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:_,createMode:h,warnings:o}}function jO(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),i=[{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 s of i)if(s.enabled){if(s.values&&s.values.length>0)throw new p(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,m.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function GO(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,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=po.get(r)??r;throw new p(`Cannot combine --unset ${s} with ${Se("create",r)}`,m.USAGE)}}function qO(e){if(Oe(e))return;let t=(n,r)=>{if(Oe(e,r))return;let i=po.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;no(n,Se("create",r),s)};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 KO(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new p(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,m.USAGE)}var $w={"--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 WO(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:i,openStatus:s,type:o,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(f=>{let g=f.type==="boolean"?"<true|false>":f.type==="array"?"<json-array>":f.type==="object"?"<json-object>":f.type==="number"?"<number>":f.type==="string_array"||f.repeatable?"<value>":"<string>";return{example:`--${f.cli_flag} ${g}`,description:`--${f.cli_flag} maps to ${f.metadata_key} (${f.type}${f.repeatable?", repeatable":""})`}}),l=[Mw(n,r,i,s),...d.map(f=>f.example)].join(" "),u=[`Run "pm create --help --type ${o}" for type-aware required option guidance.`,...t.filter(f=>f==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+o+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Ow.has(o)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(f=>f.description).join("; ")}.`);let _=[...new Set(t.flatMap(f=>{let g=f.split(" ",1)[0],y=$w[g];return y?[y]:[]}))];_.length>0&&u.push(`If the truthful value is an empty collection, use ${_.join(", ")} instead of inventing metadata.`);let h=t.length===1?`Missing required option ${t[0]} for type "${o}"`:`Missing required options ${t.join(", ")} for type "${o}"`;throw new p(h,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${o}" in one invocation.`,examples:[..._.map(f=>`pm create --type ${o} ${f} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[..._,...t,"--create-mode progressive"]}:void 0})}function zO(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?ai(t.tags):[];return di(n,t.addTags)}function BO(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new p("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,r=Jt(e,"order",n,i=>ge(i,"order"));if(r!==void 0&&!Number.isInteger(r))throw new p("Order must be an integer",m.USAGE);return r}function HO(e,t,n,r,i,s){if(r.completedAt!==void 0&&e!==t.close_status)throw new p("--completed-at requires a terminal create status.",m.USAGE);let o=e!==t.close_status?void 0:r.completedAt===void 0?s:le(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:o,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:i}:{explicit:r.closeReason};return{closeReason:sd(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:o,warnings:[]}}async function VO(e){let{pmRoot:t,type:n,id:r,settings:i,typeRegistry:s,author:o,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:_,similarityCandidate:h,allowDuplicate:f}=e,g=Zl(t,n,r,i.item_format,s.type_to_folder),y=ot(t,r),w=oe(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(A=>$s(A.kind,w)),k=await Vs({pmRoot:t,author:o,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:b}),C=b,S=[];try{let A=await mn(t,r,i.locks.ttl_seconds,o,!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let v=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await Ee(t,i.item_format,s.type_to_folder,void 0,i.schema):void 0,T=await V(t,r,i.id_prefix,i.item_format,s.type_to_folder);if(T)throw new p(`Item "${r}" already exists`,m.CONFLICT,{code:"item_already_exists",id:T.id,path:T.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${T.id}.`]});if(v){Fs(v,[...v,c.metadata],w);let $=q(i.schema);Bi(v,[...v,c.metadata],r,he=>fe(he,$),w)}let L=await fm({pmRoot:t,settings:i,operation:"create",author:o,before:null,after:c});await bu({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:bm({pmRoot:t,settings:i,typeToFolder:s.type_to_folder})});let N=await wm(t,o,{required:i.governance.duplicate_detection_mode==="strict"&&f!==!0}),E=[];try{i.governance.duplicate_detection_mode==="strict"&&f!==!0&&await rc(h,{pmRoot:t,mode:"strict",threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:!1}),await Le(g,Nu(c,{format:i.item_format,schema:i.schema,extensionFieldNames:a}));try{let $=nm({nowIso:_,author:o,op:"create",before:d,after:c,message:l,context:L.decisions.length===0?void 0:{workflow_policies:L.decisions}});await rm(y,$)}catch($){throw await zl(g),$}C&&(await k(),C=!1),E=await vm({pmRoot:t,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:g,document:c})}finally{await N()}S=[...L.warnings,...v?Ps(v,[...v,c.metadata],r):[],...E,...await ct({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await ct({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],wu({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:vu(c.metadata,u),changed_fields:u})}finally{await A()}}finally{C&&await k()}return S}async function yB(e,t){e=ar("create",e);let n=Lw(await fO(e)),r=R(process.cwd(),t.path);await F(r);let i=await x(r),s=q(i.schema),o=ln(i.schema),a=P(i,M()),c=await UO(n,t,r,i,a);n=c.resolvedOptions;let{typeDefinition:d,type:l,createMode:u}=c,_=nO(n.unset,o),{explicitUnsets:h,clearOptionKeys:f}=jO(n,_);GO(n,_),qO(n);let g=U(be(n.author),i.author_default),y=wO(d,n,u,f,g),w=I(),b=rO(n.dep,w,i.id_prefix,g),k=Qt("--comment",n.comment,w,g),C=Qt("--note",n.note,w,g),S=Qt("--learning",n.learning,w,g),A=fd(n.file),v=hd(n.test);v.values=await Dn(v.values,g,w);let T=gd(n.doc),L=sO(n.reminder,w),N=oO(n.event,w),E=pO(n.typeOption),$=Yn(l,E.values,a),he=M(),ce=kt(he),de=Ei(n.field,he,Zs,eo(o,"create",n)),_e=Iu(n,o,l),rn=new Set(_e.missing_required_flags),Bn=o.definitions.filter(J=>rn.has(`--${J.cli_flag}`));KO(de,_e,_);let rt=vO($.errors,l),Ne=rt.map(J=>`--type-option ${J}=<value>`),yt=[...new Set([...y,...Ne,..._e.missing_required_flags])].sort((J,Vo)=>J.localeCompare(Vo));WO({combinedMissingFlags:yt,typeDefinition:d,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:rt,openStatus:s.open_status,type:l,createMode:u,missingRequiredRuntimeFields:Bn}),kO($.errors,l,d,s);let ke=await MO({pmRoot:r,settings:i,typeRegistry:a,explicitId:n.id}),Me=n.status!==void 0?ZI(n.status,s):eO(d,s),wt=n.priority!==void 0?Ni(n.priority):2,O=_.metadataKeys,it=zO(O,n),vt=Jt(O,"deadline",n.deadline,J=>le(J,new Date(w),"deadline")),Y=Jt(O,"estimated_minutes",n.estimatedMinutes,J=>ui(J,"estimated-minutes")),jo=X(O,"acceptance_criteria",n.acceptanceCriteria),Pe=X(O,"definition_of_ready",n.definitionOfReady),Go=BO(O,n),ti=X(O,"goal",n.goal),qo=X(O,"objective",n.objective),ni=X(O,"value",n.value),_k=X(O,"impact",n.impact),fk=X(O,"outcome",n.outcome),hk=X(O,"why_now",n.whyNow),gk=X(O,"assignee",n.assignee),yk=O.has("author")?void 0:be(n.author)??g,wk=X(O,"parent",n.parent),pl=await LO(wk,n,O,r),Ko=pl.parent,vk=pl.parentSource,bk=X(O,"reviewer",n.reviewer),kk=Jt(O,"risk",n.risk,J=>Ve(Ys(J),mi,"risk")),Ek=Jt(O,"confidence",n.confidence,J=>Js(J)),Sk=n.allowMissingParent===!0&&i.validation.parent_reference==="strict_error"?"warn":i.validation.parent_reference,_l=i.validation.sprint_release_format,It=[...c.warnings,...OO(l,ke,vt,L.values,N.values)],fl=await NO({itemId:ke,parent:Ko,pmRoot:r,settings:i,typeRegistry:a,policy:Sk});Ko=fl.parent,It.push(...fl.warnings);let hl=Iw(O,"sprint",n.sprint,"sprint",_l),Tk=hl.value;It.push(...hl.warnings);let gl=Iw(O,"release",n.release,"release",_l),Ck=gl.value;It.push(...gl.warnings);let yl=X(O,"blocked_by",n.blockedBy),wl=await PO({pmRoot:r,settings:i,typeRegistry:a,statusRegistry:s,blockedBy:yl,dependencyValues:b.values,status:Me,statusExplicit:n.status!==void 0,nowValue:w,author:g}),Wo=wl.dependencyValues;Kr(ke,Wo),It.push(...await co({pmRoot:r,dependencies:Wo,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ke,createdAt:w}],schema:i.schema})),Me=wl.status;let Ak=X(O,"blocked_reason",n.blockedReason),xk=X(O,"unblock_note",n.unblockNote),Rk=X(O,"reporter",n.reporter),Ik=Jt(O,"severity",n.severity,J=>Ve(Xs(J),pi,"severity")),Ok=X(O,"environment",n.environment),Lk=X(O,"repro_steps",n.reproSteps),vl=X(O,"resolution",n.resolution),Dk=X(O,"expected_result",n.expectedResult),Nk=X(O,"actual_result",n.actualResult),Mk=X(O,"affected_version",n.affectedVersion),Pk=X(O,"fixed_version",n.fixedVersion),$k=X(O,"component",n.component),Fk=Jt(O,"regression",n.regression,J=>Qs(J)),Uk=X(O,"customer_impact",n.customerImpact),zo=yd(n.title,"--title"),Bo=n.description??"",ri=n.body??"",bl=await rc({title:zo,description:Bo,body:ri},{pmRoot:r,mode:i.governance.duplicate_detection_mode,threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});It.push(...Ch(bl));let Ho=HO(Me,s,i,n,vl,w),jk=Ho.closeReason,Gk=Me===s.close_status?w:void 0,qk=Ho.completedAt;It.push(...Ho.warnings);let ii=Du({id:ke,title:zo,description:Bo,type:l,type_options:$.normalized,status:Me,closed_at:Gk,completed_at:qk,close_reason:jk,priority:wt,tags:it,created_at:w,updated_at:w,deadline:vt,assignee:gk,author:yk,estimated_minutes:Y,acceptance_criteria:jo,definition_of_ready:Pe,order:Go,goal:ti,objective:qo,value:ni,impact:_k,outcome:fk,why_now:hk,parent:Ko,reviewer:bk,risk:kk,confidence:Ek,sprint:Tk,release:Ck,blocked_by:yl,blocked_reason:Ak,unblock_note:xk,reporter:Rk,severity:Ik,environment:Ok,repro_steps:Lk,resolution:vl,expected_result:Dk,actual_result:Nk,affected_version:Mk,fixed_version:Pk,component:$k,regression:Fk,customer_impact:Uk,dependencies:Wo,comments:k.values,notes:C.values,learnings:S.values,files:A.values,tests:v.values,docs:T.values,reminders:L.values,events:N.values,...de,..._e.values});try{Si(ii,he)}catch(J){throw new p(J instanceof Error?J.message:"Invalid extension item field values",m.USAGE)}let Kk=Mu({metadata:ii,body:ri},{schema:i.schema,extensionFieldNames:ce}),Wk={metadata:{},body:""},kl=[...h].sort((J,Vo)=>J.localeCompare(Vo)),zk=cO(n.message,kl),El=aO(ii,ri,kl,[...Object.keys(de),...Object.keys(_e.values??{})]),Bk=await VO({pmRoot:r,type:l,id:ke,settings:i,typeRegistry:a,author:g,extensionFieldNames:ce,afterDocument:Kk,beforeDocument:Wk,historyMessage:zk,changedFields:El,nowValue:w,similarityCandidate:{title:zo,description:Bo,body:ri},allowDuplicate:n.allowDuplicate}),Sl=structuredClone(ii);u==="strict"&&h.has("dependencies")&&(Sl.dependencies=[]);let Hk=hw(ke,l,Me,s);return Pw(l,vt,L.values,N.values)&&tm(`[pm] warning: ${l} '${ke}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ke} --deadline <ISO>' or 'pm update ${ke} --event "start=<ISO>,end=<ISO>"'.`),{item:Sl,changed_fields:El,warnings:[...It,...Bk],...Object.fromEntries([["parent_source",vk],["next_transition",Hk],["similarity_advisory",bl]].filter(J=>J[1]!==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]="f4c54507-c8b1-5f19-b58a-61186c79c8b0")}catch{}})();function Zt(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Ke("in_progress",e)??e.open_status}import{AsyncLocalStorage as YO}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]="a49a1fae-4705-55b4-b4d7-8aa2b4fbfe89")}catch{}})();var XO="strict",Fw="start_blocked_by_open_dependency";function Uw(e,t,n){if(t===void 0)return!1;let r=Mt(Zt(n),n);return Mt(t,n)===r&&Mt(e??"",n)!==r}function wd(e,t,n){let r=i=>Ze(i.trim(),n).toLowerCase();return r(e)===r(t)}function JO(e,t,n){let r=e.dependencies??[],i=r.filter(o=>o.kind==="blocked_by");if(r.some(o=>o.kind!=="blocked_by"&&Qn(o.kind)==="blocked_by"&&wd(o.id,t,n)))return W(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&wd(e.blocked_by,t,n))){let o=i.filter(a=>wd(a.id,t,n));return o.length===1&&o.every(a=>a.id===gn(a.id,n,void 0))?W(["update",e.id,"--dep-remove",`id=${o[0].id},kind=blocked_by`]):W(["get",e.id,"--fields","blocked_by,dependencies"])}let s=o=>o.trim().toLowerCase();return i.every(o=>s(o.id)===s(String(e.blocked_by)))?W(["update",e.id,"--unset","blocked_by"]):W(["get",e.id,"--fields","blocked_by,dependencies"])}var QO=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function ZO(e,t){try{return(await $m(e)).filter(n=>!n.resolved)}catch(n){let r=xm(n)?n.context.code:void 0;if(!t||typeof r!="string"||!QO.has(r))throw n;return r}}async function jw(e){let t=e.settings.governance.start_blocker_enforcement??XO;if(t==="off")return[];let n=P(e.settings,M()).type_to_folder,r=e.metadata.id,i=await ZO({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof i=="string")return[`start_blocker_unverifiable:${r}:${i}`];if(i.length===0)return[];let s=i.map(o=>o.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${s}`];if(e.force===!0)return[`start_blocker_override:${r}:${s}`];throw new p(`Cannot start ${r}: ${i.length===1?"its blocker":`${i.length} of its blockers`} ${s} ${i.length===1?"is":"are"} still open.`,m.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${i.length===1?"":"s"} first, remove the blocked_by edge if it no longer applies, or start anyway with --force.`,why:"Starting work that a declared blocker still gates would leave an in-progress item that validate reports as non_blocked_status_has_blocked_by. governance.start_blocker_enforcement (strict by default) governs this check.",nextSteps:[...i.filter(o=>o.external!==!0).slice(0,3).map(o=>W(["get",o.id])),JO(e.metadata,i[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:i.map(o=>({id:o.id,title:o.title,status:o.status,external:o.external===!0}))}})}async function ho(e){if(e.requested===!1||!Uw(e.fromStatus,e.metadata.status,e.registry))return[];let t=await jw(e),n=vd.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var vd=new YO;function Gw(e){return vd.run({warnings:new Set},e)}async function qw(e){let t=vd.getStore();if(t===void 0)return[];let n=Uw(e.metadata.status,Zt(e.registry),e.registry)?await jw(e):[];for(let r of n)t.warnings.add(r);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]="d510588a-e45d-54ba-b9c0-153940bb6677")}catch{}})();var Kw="terminal_state_unchanged";function Ww(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function eL(e,t){return se(e,t)===t.close_status}function tL(e){let t=n=>io.includes(n.trim().toLowerCase());return ld(e.unset??[],t).some(t)}function zw(e){!e.settings.governance.require_close_reason||!tL(e.options)||Ns({explicit:e.options.closeReason},!0)}function bd(e,t,n,r=!1){if(!eL(e.status,n))return!1;let i=Ww(t.closeReason);return r&&t.closeReason!==void 0&&i===void 0||i!==void 0&&i!==Ww(e.close_reason)?!1:t.completedAt===void 0||le(t.completedAt,new Date,"completed-at")===e.completed_at}async function Bw(e){let t=await V(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 ue(t,{schema:e.settings.schema});return n.metadata}async function Hw(e,t,n,r,i){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Kw]};let s=Je(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),o=await r(e.id,s,e.global);return bd(o.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:o.item,changed_fields:o.changed_fields,warnings:[...e.workflowTransitionWarnings,...o.warnings,Kw]}:i(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]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function $n(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=cm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Ke(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Ke(e.toStatus,e.statusRegistry)??e.toStatus,i=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${dm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new p(i,m.USAGE);return`workflow_transition_not_allowed: ${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]="d070a3f3-93a4-5bec-9bb1-12431b497174")}catch{}})();var Td=[...cd,{canonical:"close-reason",aliases:io,optionKey:"closeReason",metadataKey:"close_reason"},...dd,...so],nL=(()=>{let e=new Map;for(let t of Td)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),go=new Map(Td.map(e=>[e.optionKey,e.canonical])),rL=Td.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),iL=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),sL=to({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function nv(e){if(Oe(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s},r=new Set([...go.keys(),"rank"]);for(let i of r){if(Oe(e,i))continue;let s=t[i];if(typeof s!="string"||!He(s))continue;let o=i==="rank"?"order":go.get(i)??i;n(o),t[i]=void 0}return Je(e,ro(t,sL))}function gH(e,t,n,r=["update"]){return[...Cd([...e],t,n,r).metadataKeys]}function Cd(e,t,n=[],r=["update"]){return oo({raw:e,supportedFields:rL,resolveDefinition:i=>{let s=n.find(o=>{let a=o.toLowerCase();return a===i||a.replaceAll("_","-")===i||a.replaceAll("-","_")===i});return nL.get(i)??r.map(o=>ao(i,o,t)).find(o=>o!==void 0)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Vw=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 Yw(e){let t=e.disallowedFlags.flatMap(r=>{let i=Vw.get(r);return i?[i(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let i=Vw.get(r);return i?[`Replace ${r} with: ${i(e.id)}`]:[]});return new p(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function oL(e,t,n){let r=t.ownershipMetadataBypass===!0,i=t.ownershipDependencyBypass===!0;if(!r&&!i)return;if(r&&i)throw new p("Choose only one package-provided ownership bypass mode.",m.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(i){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new p("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw Yw({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 o=[];s(t.status!==void 0,"--status",o),s(t.closeReason!==void 0,"--close-reason",o),s(t.assignee!==void 0,"--assignee",o),s(t.parent!==void 0,"--parent",o),s(t.blockedBy!==void 0,"--blocked-by",o),s(t.blockedReason!==void 0,"--blocked-reason",o),s(t.unblockNote!==void 0,"--unblock-note",o),s(t.dep!==void 0,"--dep",o),s(t.depRemove!==void 0,"--dep-remove",o),s(t.replaceDeps===!0,"--replace-deps",o),s(t.replaceTests===!0,"--replace-tests",o),s(t.replaceFiles===!0,"--replace-files",o),s(t.replaceDocs===!0,"--replace-docs",o),s(t.note!==void 0,"--note",o),s(t.learning!==void 0,"--learning",o),s(t.test!==void 0,"--test",o),s(t.reminder!==void 0,"--reminder",o),s(t.event!==void 0,"--event",o),s(t.clearDeps===!0,"--clear-deps",o),s(t.clearComments===!0,"--clear-comments",o),s(t.clearNotes===!0,"--clear-notes",o),s(t.clearLearnings===!0,"--clear-learnings",o),s(t.clearFiles===!0,"--clear-files",o),s(t.clearTests===!0,"--clear-tests",o),s(t.clearDocs===!0,"--clear-docs",o),s(t.clearReminders===!0,"--clear-reminders",o),s(t.clearEvents===!0,"--clear-events",o);let a=[...n].filter(c=>iL.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(o.push(...a),o.length>0)throw Yw({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: ${o.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:o})}function aL(e,t){let n=se(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function cL(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:rv(e)}function rv(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new p(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function Fn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var dL=["id","kind","type","author","created_at","source_kind"],lL=["id","kind","type","author","created_at","source_kind"];function iv(e){return e.startsWith("```")||e.includes(`
|
|
11
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:sn(e)}function sv(e){return typeof e=="string"?oe().resolve(e)?.kind??e.trim():e}function uL(e,t,n,r){return e?(Ie(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let s=i.trim(),o=iv(s);qr(s,o);let a=o?Q(i,"--dep"):{id:s,kind:"related"};o&&we(a,"--dep",dL);let c=a.id?.trim(),d=sv((a.kind??a.type)?.trim());if(!c||!d)throw new p("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(c.toLowerCase()==="undefined")throw new p(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=dr(Fn(a.source_kind)),u=Fn(a.author);return{id:lr(c,t,l),kind:Gr(d),created_at:cL(a.created_at,n),author:u??r,source_kind:l??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function mL(e,t){return e?(Ie(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new p("--dep-remove requires id or key/value selectors",m.USAGE);let i=iv(r);if(qr(r,i,"--dep-remove"),i){let s=Q(r,"--dep-remove");we(s,"--dep-remove",lL);let o=s.id?.trim();if(!o)throw new p("--dep-remove key/value form requires id=<value>",m.USAGE);if(o.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${o}"`,m.USAGE);let a=sv(Fn(s.kind??s.type)),c=dr(Fn(s.source_kind)),d=Fn(s.author),l=Fn(s.created_at);return{id:lr(o,t,c),kind:a?Gr(a):void 0,source_kind:c,author:d,created_at:l?rv(l):void 0}}if(r.toLowerCase()==="undefined")throw new p(`--dep-remove id must not use placeholder token "${r}"`,m.USAGE);return{id:Ze(r,t)}})):[]}function yo(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function pL(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",i=Date.parse(r),s=Number.isFinite(i)?new Date(i).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function _L(e,t,n,r){let i=[...e??[]],s=!1;if(t===void 0){let o=i.filter(a=>a.kind!=="blocked_by");return o.length!==i.length&&(i=o,s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}return i.some(o=>o.kind==="blocked_by"&&o.id===t)||(i.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}async function fL(e,t,n,r,i,s){if(e===void 0||t)return{};let o=e.trim();if(o.length===0)return{};let a=await V(n,Ze(o,r),r,i,s);return a?{id:a.id}:{unresolved:o}}function hL(e,t,n,r,i){let s=_L(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,i.includes("dependencies")||i.push("dependencies"))}function gL(e){return`${e.path}::${e.scope}`}function yL(e){return`${e.path}::${e.scope}`}function wL(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function ov(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 Xw(e,t){let n=Vn("update",e);if(!n)throw new p(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function vL(e,t,n){let r=new Set,i=(s,o)=>{o&&r.add(s)};if(i("title",e.title!==void 0),i("description",e.description!==void 0),i("body",e.body!==void 0),i("status",e.status!==void 0),i("closeReason",e.closeReason!==void 0),i("priority",e.priority!==void 0),i("type",e.type!==void 0),i("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),i("deadline",e.deadline!==void 0),i("estimatedMinutes",e.estimatedMinutes!==void 0),i("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),i("definitionOfReady",e.definitionOfReady!==void 0),i("order",e.order!==void 0||e.rank!==void 0),i("goal",e.goal!==void 0),i("objective",e.objective!==void 0),i("value",e.value!==void 0),i("impact",e.impact!==void 0),i("outcome",e.outcome!==void 0),i("whyNow",e.whyNow!==void 0),i("author",e.author!==void 0),i("message",e.message!==void 0),i("assignee",e.assignee!==void 0),i("parent",e.parent!==void 0),i("reviewer",e.reviewer!==void 0),i("risk",e.risk!==void 0),i("confidence",e.confidence!==void 0),i("sprint",e.sprint!==void 0),i("release",e.release!==void 0),i("blockedBy",e.blockedBy!==void 0),i("blockedReason",e.blockedReason!==void 0),i("unblockNote",e.unblockNote!==void 0),i("reporter",e.reporter!==void 0),i("severity",e.severity!==void 0),i("environment",e.environment!==void 0),i("reproSteps",e.reproSteps!==void 0),i("resolution",e.resolution!==void 0),i("expectedResult",e.expectedResult!==void 0),i("actualResult",e.actualResult!==void 0),i("affectedVersion",e.affectedVersion!==void 0),i("fixedVersion",e.fixedVersion!==void 0),i("component",e.component!==void 0),i("regression",e.regression!==void 0),i("customerImpact",e.customerImpact!==void 0),i("dep",e.dep!==void 0),i("depRemove",e.depRemove!==void 0),i("dep",e.replaceDeps===!0),i("comment",e.comment!==void 0),i("note",e.note!==void 0),i("learning",e.learning!==void 0),i("file",e.file!==void 0),i("test",e.test!==void 0),i("test",e.replaceTests===!0),i("file",e.replaceFiles===!0),i("doc",e.replaceDocs===!0),i("doc",e.doc!==void 0),i("reminder",e.reminder!==void 0),i("event",e.event!==void 0),i("typeOption",e.typeOption!==void 0),i("field",e.field!==void 0),i("force",e.force===!0),i("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),i("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),i("dep",e.clearDeps===!0),i("comment",e.clearComments===!0),i("note",e.clearNotes===!0),i("learning",e.clearLearnings===!0),i("file",e.clearFiles===!0),i("test",e.clearTests===!0),i("doc",e.clearDocs===!0),i("reminder",e.clearReminders===!0),i("event",e.clearEvents===!0),i("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=Cd(e.unset,t,n,e.runtimeFieldCommands);for(let o of s.optionKeys)i(o,!0)}return r}function bL(e,t,n,r,i){let s=_i(e,n);if(!s)throw new p(`Invalid type value "${e}"`,m.USAGE);let o=cn(s,"update",[]);if(o.errors.length>0)throw new p(o.errors.join("; "),m.CONFLICT);let a=vL(t,r,i);for(let c of o.disabled)if(a.has(Xw(c,e)))throw new p(`Option ${Se("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of o.required)if(!a.has(Xw(c,e)))throw new p(`Missing required option ${Se("update",c)} for type "${e}"`,m.USAGE)}var kL=new Set(["order","rank"]),EL=Zo.filter(e=>!kL.has(e)),av=["tags","closeReason",...EL],SL=["title","description","body","status","closeReason","completedAt","priority","type",...Zo,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],TL=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>le(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>ui(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"}],CL=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ve(Ys(e),mi,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Js(e)}],AL=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ve(Xs(e),pi,"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=>Qs(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Sd(e,t,n){for(let r of e){let i=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(i===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof i!="string")throw new p(`${Se("update",String(r.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(i,n):i.trim(),n.changedFields.push(r.metadataKey)}}}async function xL(e){return nv(await li(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 RL(e){return e=ar("update",e),Dt(e)?await xL(e):nv(e)}function IL(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 kd(e){if(e.enabled&&(!e.values||e.values.length===0))throw new p(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new p(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function OL(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new p("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.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 p("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new p("--replace-deps cannot be combined with --dep-remove",m.USAGE);kd({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),kd({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),kd({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function LL(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 p(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function DL(e){let t={};for(let n of av)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function NL(e,t){let n=DL(e);for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=go.get(r)??r;throw new p(`Cannot combine --unset ${s} with ${Se("update",r)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new p("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new p("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new p("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function ML(e){if(Oe(e))return;let t=(n,r)=>{if(Oe(e,r))return;let i=go.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;no(n,Se("update",r),s)};for(let n of av)t(e[n],String(n));t(e.order??e.rank,"order"),Ie(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ie(e.event,"--event","Use --clear-events to clear linked events.")}function PL(e,t){let n={};for(let r of SL)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 $L(e){let t=await V(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 ue(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function FL(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return Ee(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function UL(e){e.before&&(Fs(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Bi(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>fe(t,e.statusRegistry),oe()))}function jL(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new p("--order and --rank must match when both are provided",m.USAGE)}async function GL(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=gn(Oi(e.options.parent),e.settings.id_prefix);if(ji(t))return{resolvedParentValue:t,warnings:[]};if(Di(e.id,t,e.settings.id_prefix),await V(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=Ze(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Li(n,e.parentReferencePolicy).warnings}}function qL(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function KL(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await V(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 ue(t,{schema:e.settings.schema}),r=e.options.type!==void 0?st(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",i=$n({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return i?[i]:[]}async function WL(e){if(!e.fieldFlags.status||se(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;zw(e);let t=Object.entries(e.fieldFlags).filter(([i,s])=>s&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),n=await Bw(e);if(bd(n,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Hw(e,n,t,Wr,i=>Jw(e,i));let r;if(t.length>0){let i=Je(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});r=await Wr(e.id,i,e.global)}return Jw(e,r)}async function Jw(e,t){let n=await Ms(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),r=[...e.workflowTransitionWarnings,...t?.warnings??[],...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:r}}function zL(e,t,n,r){return t.title!==void 0&&(e.metadata.title=yd(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")),se(e.metadata.status,n)??e.metadata.status}var BL=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function HL(e,t){for(let n of BL)e[n]!==void 0&&(delete e[n],t.push(n))}function VL(e,t,n,r,i){let s=aL(n,t.statusRegistry);if(e.metadata.status=s,i.push("status"),s===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,i.push("closed_at","completed_at");return}!fe(s,t.statusRegistry)&&fe(r,t.statusRegistry)&&HL(e.metadata,i)}function YL(e,t,n,r){if(t.options.status!==void 0&&VL(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!fe(e.metadata.status,t.statusRegistry))throw new p("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=le(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function XL(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 i=t.options.closeReason?.trim()??"";if(i.length===0)throw new p("--close-reason must not be empty",m.USAGE);e.metadata.close_reason=i}r.push("close_reason");return}t.options.status!==void 0&&fe(n,t.statusRegistry)&&!fe(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function JL(e,t,n,r){YL(e,t,n,r),XL(e,t,n,r)}function QL(e,t,n){let r=st(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Ni(t.options.priority),n.push("priority")),t.options.type!==void 0){let i=st(t.options.type,t.typeRegistry);if(!i)throw new p(Pi(t.options.type,t.typeRegistry.types,Ti(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=i,r=i,n.push("type")}return bL(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),ZL(e,t,r,n),r}function ZL(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 s=mo(t.options.typeOption??[]),o=Yn(n,s,t.typeRegistry);if(o.errors.length>0)throw new p(o.errors.join("; "),m.USAGE);e.metadata.type_options=o.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let i=Yn(n,e.metadata.type_options,t.typeRegistry);if(i.errors.length>0)throw new p(`Current type options are incompatible with type "${n}". ${i.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=i.normalized}function eD(e,t){let n=new Set(t.map(i=>yo(i))),r=new Set;return e.filter(i=>{if(!n.has(yo(i)))return!0;let s=pL(i);return r.has(s)?!1:(r.add(s),!0)})}function tD(e,t,n){let r=t.filter(i=>!e.some(s=>ov(s,i)));if(r.length!==0)throw new p(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(i=>({id:i.id,kind:i.kind,source_kind:i.source_kind,author:i.author,created_at:i.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 nD(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=eD(r,t.dependencyUpdates.additions);let i=new Set(r.map(s=>yo(s)));for(let s of t.dependencyUpdates.additions){let o=yo(s);i.has(o)||(r.push(s),i.add(o))}}t.dependencyRemovals.length>0&&(tD(r,t.dependencyRemovals,e.metadata.id),r=r.filter(i=>!t.dependencyRemovals.some(s=>ov(i,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function rD(e,t,n){Ed(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Ed(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Ed(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Ed(e,t,n,r,i,s){n===void 0&&!i.has(t)||(i.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function iD(e,t,n){Qw(e,"files",t.options.file,t.fileUpdates.values,gL,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),sD(e,t,n),Qw(e,"docs",t.options.doc,t.docUpdates.values,yL,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Qw(e,t,n,r,i,s,o,a){if(!(n===void 0&&!o.has(t))){if(s)e.metadata[t]=r;else if(o.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>i(l)));for(let l of r){let u=i(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function sD(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Zw(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Zw([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Zw(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let i=wL(r);n.has(i)||(t.push(r),n.add(i))}return t}function oD(e,t,n){let r=t.options.addTags,i=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(i)&&i.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let o=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?ai(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Wl(di(o,r),i),n.changedFields.push("tags")}Sd(TL,t.options,n),cD(e,t,n.changedFields)}function aD(e,t,n){let r=t.options.addAc,i=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(i)&&i.length>0))return;let s=Kl(ci(e.metadata.acceptance_criteria),r,i);if(s.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.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 o=s.criteria.join("; ");e.metadata.acceptance_criteria!==o&&(o===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=o,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function cD(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 i=ge(r??"","order");if(!Number.isInteger(i))throw new p("Order must be an integer",m.USAGE);e.metadata.order=i}n.push("order")}}function dD(e,t,n,r){lD(e,t,n.changedFields),uD(e,t,n.changedFields),Sd(CL,t.options,n),ev(e,t,"sprint",r,n.changedFields),ev(e,t,"release",r,n.changedFields),mD(e,t,n.changedFields),Sd(AL,t.options,n)}function lD(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 p("--assignee must not be empty. Use --unset assignee to clear it.",m.USAGE);e.metadata.assignee=r}n.push("assignee")}}function uD(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 ev(e,t,n,r,i){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=Mi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}i.push(n)}}function mD(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)&&hL(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function pD(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=lo(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=uo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function _D(e,t,n){tv(e,t.runtimeFieldRegistry.definitions.map(i=>i.metadata_key),t.clearItemMetadataKeys,n),tv(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[i,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(i)){let o=i.replaceAll("_","-"),a=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===i)?.cli_flag??o;throw new p(`Cannot combine --unset ${o} with --${a}`,m.USAGE)}$e(e[i],s)||(e[i]=s,n.push(i))}let r=Ei(t.options.field,t.extensionRegistrations,Zs,eo(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let i of Object.keys(r))if(t.clearItemMetadataKeys.has(i))throw new p(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,m.USAGE);for(let[i,s]of Object.entries(r))$e(e[i],s)||(e[i]=s,n.push(i))}function tv(e,t,n,r){for(let i of t)!n.has(i)||e[i]===void 0||(delete e[i],r.push(i))}function fD(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(i=>{let s=t[i];return s!==void 0&&(!Array.isArray(s)||!$e(s,n[i]??[]))});if(r!==void 0)throw new p(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,m.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 hD(e,t){fD(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,i=[],s=[],o=zL(e,t.options,t.statusRegistry,i),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:i,nowValue:t.nowValue};JL(e,t,o,i),QL(e,t,i),nD(e,t,i),rD(e,t,i),iD(e,t,i),oD(e,t,c),aD(e,t,c),dD(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Kr(e.metadata.id,e.metadata.dependencies),se(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,i.includes("assignee")||i.push("assignee")),pD(e,t,i),_D(a,t,i);try{Si(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new p(u instanceof Error?u.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(i)].filter(u=>u==="body"?e.body!==r:!$e(n[u],d[u]));return t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${ci(n.acceptance_criteria).length}:${ci(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function cv(e,t,n,r={}){or(e,"update","id"),t=await RL(t);let i=R(process.cwd(),n.path);await F(i);let s=await x(i),o=q(s.schema),a=ln(s.schema),c=M(),d=kt(c),l=P(s,c),u=s.governance.workflow_enforcement??"off",_=u==="off"?[]:fn(s.schema),h=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],f=Cd(t.unset,a,d,t.runtimeFieldCommands),g=new Set(f.optionKeys),y=new Set(f.metadataKeys);OL(t),LL({definitions:IL(t),options:t,clearOptionKeys:g,clearItemMetadataKeys:y}),oL(e,t,y),NL(t,f),ML(t);let w=U(t.author,s.author_default),b=new Date,k=b.toISOString(),C=uL(t.dep,s.id_prefix,k,w);Kr(e,C.additions);let S=await co({pmRoot:i,dependencies:C.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:l.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),A=mL(t.depRemove,s.id_prefix),v=Qt("--comment",t.comment,k,w),T=t.ownershipMetadataBypass===!0&&v.values?{...v,values:v.values.map(O=>({...O,author:w}))}:v,L=Qt("--note",t.note,k,w),N=Qt("--learning",t.learning,k,w),E=fd(t.file),$=hd(t.test);$.values=await Dn($.values,w,k);let he=gd(t.doc),ce=[],de=await GL({id:e,options:t,unsetTargets:f,pmRoot:i,settings:s,typeRegistry:l,parentReferencePolicy:h}),_e=await fL(t.blockedBy,y.has("blocked_by"),i,s.id_prefix,s.item_format,l.type_to_folder),rn=_e.id,Bn=[...de.warnings,...qL(_e)],rt=Ou(t,a,t.runtimeFieldCommands),Ne=PL(t,rt);if(!Object.values(Ne).some(Boolean))return $L({pmRoot:i,id:e,settings:s,typeRegistry:l});ce.push(...await KL({options:t,fieldFlags:Ne,workflowEnforcement:u,typeWorkflows:_,statusRegistry:o,typeRegistry:l,pmRoot:i,id:e,settings:s}));let yt=await WL({options:t,fieldFlags:Ne,statusRegistry:o,workflowTransitionWarnings:ce,global:n,id:e,pmRoot:i,settings:s,typeRegistry:l});if(yt)return yt;jL(t);let ke=oe(),Me=Ne.parent&&!y.has("parent")||C.additions.some(O=>$s(O.kind,ke)),wt=await Vs({pmRoot:i,author:w,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Me});try{let O=await FL({fieldFlags:Ne,clearedMetadataKeys:y,pmRoot:i,settings:s,typeToFolder:l.type_to_folder}),it,vt,Y=await hn({pmRoot:i,settings:s,typeToFolder:l.type_to_folder,id:e,op:gD(t,r),author:w,message:t.message,resolveHistoryContext:()=>vt,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,async mutate(Pe){let Go=Pe.metadata.status;it=yD({document:Pe,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:o}),vt=it?{recurrence:it}:void 0,O=O?.map(ni=>ni.id===Pe.metadata.id?structuredClone(Pe.metadata):ni);let ti=hD(Pe,{options:t,settings:s,typeRegistry:l,statusRegistry:o,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:y,dependencyUpdates:C,dependencyRemovals:A,commentUpdates:T,noteUpdates:L,learningUpdates:N,fileUpdates:E,testUpdates:$,docUpdates:he,resolvedParentValue:de.resolvedParentValue,resolvedBlockedByDependencyId:rn,runtimeFieldUpdates:rt,nowValue:b,nowIso:k,author:w,pmRoot:i});UL({before:O,document:Pe,statusRegistry:o});let qo=await ho({pmRoot:i,settings:s,metadata:Pe.metadata,fromStatus:Go,registry:o,force:t.force===!0});return{...ti,warnings:[...ti.warnings,...qo]}}});await wt();let jo=O?Ps(O,O.map(Pe=>Pe.id===Y.item.id?Y.item:Pe),Y.item.id):[];return{item:Y.item,changed_fields:Y.changedFields,warnings:[...ce,...Bn,...S,...jo,...Y.warnings],...it===void 0?{}:{lifecycle_transition:it}}}finally{await wt()}}function gD(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function yD(e){if(e.recurrenceReason===void 0)return;let t=se(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!fe(t,e.statusRegistry))throw new p(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.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=se(n,e.statusRegistry)??n,i=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(o=>{let a=i[o];return typeof a=="string"?[[o,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function Wr(e,t,n){return cv(e,t,n)}async function yH(e,t,n,r){or(r,"reopen","reason");let i=await cv(e,t,n,{recurrenceReason:r});if(i.lifecycle_transition===void 0)throw new p(`Item ${e} did not produce the required recurrence receipt.`,m.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{...i,lifecycle_transition:i.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]="146c927e-4db7-5a69-a715-c6996983f5f8")}catch{}})();function wD(e){return e===void 0?"unknown":e==="claim"?"claim":"assignment"}async function Ad(e,t,n){let r=[...await Promise.resolve().then(()=>dt(ot(e,t),t)).catch(()=>[])].reverse().find(a=>a.patch.some(c=>c.path==="/metadata/assignee")),i=r?.patch.find(a=>a.path==="/metadata/assignee"),s=i!==void 0&&typeof i.value=="string"&&i.value.trim()===n.trim()?r:void 0,o=wD(s?.op);return{phrase:o==="claim"?`claimed by ${n}`:`assigned to ${n}`,holder:n,source:o,since:s?.ts??null}}async function kH(e,t,n){return(await Ad(e,t,n)).phrase}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function wo(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new p("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Ke(e.handoff,t):void 0;if(n===void 0||Et(n,t)||n===t.in_progress_status)throw new p("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new p("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function dv(e,t,n,r,i){if(Et(e.status,r)||!e.assignee?.trim())throw new p("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let s=n.governance.workflow_enforcement??"off",o=$n({enforcement:s,typeWorkflows:s==="off"?[]:fn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:i},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:o?[o]:[],changedFields:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4021f6b1-2156-5057-b41c-b1c8847aca7a")}catch{}})();var lv="no_available_next_item";function vD(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 xd(e,t,n,r={}){let i=R(process.cwd(),n.path);await F(i);let s=await x(i),o=q(s.schema),a=U(r.author,s.author_default),c=aa(a),d=null,l=!1,u={},_=[],h=await me({pmRoot:i,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(f){let g=f.metadata.assignee??"",y=f.metadata.claim_principal?.trim()||g;if(d=g.trim().length>0?g:null,Et(f.metadata.status,o)&&!t)throw new p(`Cannot claim terminal item ${f.metadata.id} without --force`,m.CONFLICT);if(d!==null&&y!==c){if(r.ifAvailable===!0)return l=!0,_.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let v=await Ad(i,f.metadata.id,g);throw new p(`Item ${f.metadata.id} is already ${v.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",item_id:f.metadata.id,claimed_by:v.holder,claimed_at:v.since,claim_source:v.source,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."]})}_.push(`claim_takeover:${d}->${a}`)}let w={assignee:a,claim_principal:c},b=["assignee","claim_principal"].filter(v=>f.metadata[v]!==w[v]);Object.assign(f.metadata,w);let k=f.metadata.status,{changedFields:C,warnings:S,...A}=SD(f.metadata,r.start===!0,s,o);return S.push(...await ED({pmRoot:i,settings:s,metadata:f.metadata,fromStatus:k,registry:o,force:t,start:r.start===!0})),u=A,_.push(...S),{changedFields:[...b,...C],warnings:_}}});return l||_.push(...await kD({pmRoot:i,settings:s,principal:c,itemId:h.item.id})),{item:h.item,changed_fields:h.changedFields,claimed_by:l&&d!==null?d:a,previous_assignee:d,forced:t,...l?{skipped:!0}:{},..._.length>0?{warnings:_}:{},...u}}var bD="claim_semantic_attribution_unrecorded";async function kD(e){try{return await tf(e),[]}catch{return[bD]}}function GH(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new p(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",m.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new p("Specify either an item id or --next, not both",m.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}async function ED(e){return e.start?ho(e):qw(e)}function SD(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(Et(e.status,r))throw new p(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,m.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let i=Zt(r),s=n.governance.workflow_enforcement??"off",o=$n({enforcement:s,typeWorkflows:s==="off"?[]:fn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:i}),a={from_status:e.status,to_status:i},c=e.status===i?[]:["status"];return e.status=i,{start:a,changedFields:c,warnings:o?[o]:[]}}async function qH(e,t,n={},r={}){let i=TD(n.maxAttempts),s=await x(R(process.cwd(),t.path)),o={...n,author:U(n.author,s.author_default)},a=await rf({...r,callerAuthor:o.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return CD(c.slice(0,i),e,t,o)}function TD(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new p("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function CD(e,t,n,r={},i=xd){let s=0;for(let a of e){s+=1;try{let c=await i(a.id,t,n,r),d={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!vD(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:U(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[lv]};let o=s===0;throw new p(o?"No actionable items matched the selection filters":"No actionable item remained available to claim",o?m.NOT_FOUND:m.CONFLICT,{code:lv,why:o?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[o?"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 vo(e,t,n,r={}){let i=R(process.cwd(),n.path);await F(i);let s=await x(i),o=U(r.author,s.author_default),a=aa(o),c=r.ownershipReleaseBypass===!0,d=null,l=q(s.schema),u=wo(r,l);if(u!==void 0&&c)throw new p("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let _,h;try{h=await me({pmRoot:i,settings:s,id:e,op:"release",author:o,message:r.message,force:t,bypassAssigneeConflict:c,mutate(g){d=g.metadata.assignee??null;let y=u===void 0?void 0:dv(g.metadata,u,s,l,r.message);return _=y?.receipt,!d&&!g.metadata.claim_principal?{changedFields:[]}:(delete g.metadata.assignee,delete g.metadata.claim_principal,{changedFields:["assignee","claim_principal",...y?.changedFields??[]],warnings:y?.warnings})}})}catch(g){br(g,{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 nf({pmRoot:i,principal:a,itemId:h.item.id});let f=Mt(h.item.status,l)===Mt(l.in_progress_status,l);return{item:h.item,released_by:o,changed_fields:h.changedFields,previous_assignee:d,forced:t,..._===void 0?{}:{handoff:_},...h.warnings.length>0||f?{warnings:[...h.warnings,...f?["released_unclaimed_in_progress"]:[]]}:{},...f?{suggestions:[`${h.item.id} remains ${h.item.status} and unclaimed. If work is paused, run pm release ${h.item.id} --pause to move it to ${l.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]="35d9d28d-68f5-5a6d-b3e8-02424b81a4d4")}catch{}})();async function Rd(e,t,n){try{return await n()}catch(r){let i=r instanceof p?r.context:{},s=new p(r instanceof Error?r.message:String(r),r instanceof p?r.exitCode:m.GENERIC_FAILURE,{...i,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${i.why?` ${i.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...i.nextSteps??[]]});throw s.cause=r,s}}async function rV(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new p("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await x(R(process.cwd(),n.path)),i=Zt(q(r.schema));return Gw(async()=>{let s=await xd(e,t.force===!0,n,Wi(t,{},["start"])),o=s.item.id,a=await Rd(o,"claim",()=>Wr(o,Wi(t,{status:i},["assignee","start","next","ifAvailable","maxAttempts"]),n)).catch(async c=>{throw await AD(c,s,n,t.author)});return{id:o,action:"start_task",claim:s,update:a}})}async function AD(e,t,n,r){if(!(e instanceof p)||e.code!==Fw||t.previous_assignee!==null)return e;let i=String(t.item.id);try{await hm({pmRoot:R(process.cwd(),n.path),id:i,validate:o=>{if(o.metadata.assignee!==t.claimed_by||o.metadata.claim_principal!==t.item.claim_principal)throw new p("The claim this start took is no longer its own.",m.CONFLICT)}},()=>vo(i,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let s=e.cause instanceof p?e.cause:e;return new p(s.message,s.exitCode,{...s.context,why:`${s.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function iV(e,t,n){let r=await x(R(process.cwd(),n.path)),i=q(r.schema);wo({...t,pause:!0},i);let s=i.open_status,o=await Wr(e,Wi(t,{status:s},["assignee","pause"]),n),a=o.item.id,c=await Rd(a,"update",()=>vo(a,t.force===!0,n,t));return{id:a,action:"pause_task",update:o,release:c}}async function sV(e,t,n,r){let i=await Ms(e,t,n,r),s=i.item.id,o=await Rd(s,"close",()=>vo(s,n.force===!0,r,n));return{id:s,action:"close_task",close:i,release: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]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import zr from"node:crypto";import{cp as uv,lstat as xD,mkdir as en,readFile as jn,readdir as Od,rename as _v,rm as Dd,writeFile as bo}from"node:fs/promises";import G 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]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();var fv="https://schema.unbrained.dev/pm/workspace-snapshot/v1",bV=["create","list","inspect","restore","delete"],hv=G.join("runtime","workspace-snapshots"),RD=new Set(["checkpoints","locks","runtime","search","transactions"]),ID=/^[a-z0-9][a-z0-9._-]*$/,Un="sdk-workspace-transaction",Id={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},gv={renameEntry:_v,removeEntry:async e=>{await Dd(e,{recursive:!0,force:!0})}},Ld=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=await Uu(this.lockPath,Un);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await jn(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==Un||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Le(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
|
|
12
|
+
`)}finally{await t()}}};async function yv(e,t=""){let n=await Od(G.join(e,t),{withFileTypes:!0}),r=[];for(let i of n.sort((s,o)=>s.name.localeCompare(o.name))){if(t.length===0&&RD.has(i.name))continue;let s=G.posix.join(t.replaceAll(G.sep,"/"),i.name);if(i.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(i.isDirectory())r.push(...await yv(e,s));else if(i.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function wv(e){let t=await yv(e),n=zr.createHash("sha256"),r=[],i=0;for(let o of t){let a=await jn(G.join(e,o));r.push(a),i+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:fv,fingerprint:s,files:t,bytes:i},contents:r}}function mv(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
13
|
+
`).filter(t=>t.trim().length>0).length}async function OD(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let i=t.slice(r,r+32),s=await Promise.all(i.map(async o=>[o,await jn(G.join(e,o))]));for(let[o,a]of s)n.set(o,a)}return n}function Nd(e){if(!ID.test(e))throw new p("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",m.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 vv(e,t){return Zn(`workspace_snapshot_${e}`,t,{codes:{capacity:Id.capacity.code,permission:Id.permission.code,resource:Id.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 tn(e){return G.join(e,hv)}function bv(e){return new p(`Unknown workspace snapshot: ${e}`,m.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 kv(e,t){try{return JSON.parse(await jn(e,"utf8"))}catch(n){throw j(n)?bv(t):n}}async function pv(e,t,n){try{await Dd(e,{recursive:n})}catch(r){throw j(r)?bv(t):r}}async function LD(e,t,n=gv){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 DD(e,t,n,r,i){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await i?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function ND(e,t){return Nd(t),/^[a-f0-9]{64}$/.test(t)?t:(await kv(G.join(tn(e),"refs",`${t}.json`),t)).fingerprint}async function MD(e,t={}){if(t.name!==void 0&&(Nd(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new p("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",m.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 wv(e),i=tn(e),s=G.join(i,"objects",n.fingerprint),o=!1;try{o=(await xD(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&j(a)))throw a}if(!o){let a=G.join(i,"objects",`.create-${process.pid}-${zr.randomUUID()}`);await vv("create_object",async()=>{await en(G.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=G.join(a,"files",d);await en(G.dirname(l),{recursive:!0}),await bo(l,r[c])}await bo(G.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
14
|
+
`,"utf8"),await en(G.dirname(s),{recursive:!0})}),o=await LD(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=G.join(i,"refs");await en(c,{recursive:!0});let d=G.join(c,`.ref-${process.pid}-${zr.randomUUID()}`);await bo(d,`${JSON.stringify(a,null,2)}
|
|
15
|
+
`,"utf8"),await _v(d,G.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function Md(e,t){let n=await ND(e,t),r=await kv(G.join(tn(e),"objects",n,"manifest.json"),t);if(r.schema!==fv||r.fingerprint!==n)throw new p(`Snapshot manifest identity mismatch: ${t}`,m.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 PD(e){let t=tn(e),n=await Od(G.join(t,"objects")).catch(i=>{if(i instanceof Error&&"code"in i&&j(i))return[];throw i}),r=await Od(G.join(t,"refs")).catch(i=>{if(i instanceof Error&&"code"in i&&j(i))return[];throw i});return{objects:await Promise.all(n.filter(i=>/^[a-f0-9]{64}$/.test(i)).sort().map(i=>Md(e,i))),references:await Promise.all(r.filter(i=>i.endsWith(".json")).sort().map(async i=>JSON.parse(await jn(G.join(t,"refs",i),"utf8"))))}}async function $D(e,t){let n=await Md(e,t),{manifest:r,contents:i}=await wv(e),s=new Map(r.files.map((u,_)=>[u,i[_]])),o=await OD(G.join(tn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let _=s.get(u),h=o.get(u);_!==void 0&&h!==void 0&&_.equals(h)&&d.delete(u)}let l=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let _=mv(s.get(u)),h=mv(o.get(u));return{path:u,current_entries:_,target_entries:h,removed_entries:Math.max(0,_-h)}}).filter(u=>u.removed_entries>0).sort((u,_)=>u.path.localeCompare(_.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,_)=>u+_.removed_entries,0),affected_history_streams:l,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function FD(e,t,n={}){if(n.force!==!0)throw new p("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.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",i=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,o=await qu(e,Un,i,r,!1,!1,s),a=o.release,c=new Ld(fi(e,Un),r,i);c.start(),await c.refreshNow();let d,l=!1,u=!1;try{let _=await $D(e,t),h=await Md(e,t),f=await MD(e),g=h.fingerprint,y=tn(e),w=G.join(y,"objects",g,"files"),b=G.dirname(e),k=G.basename(e);d=G.join(b,`.${k}.restore-${zr.randomUUID()}`);let C=G.join(b,`.${k}.backup-${zr.randomUUID()}`);await vv("restore_stage",async()=>{await en(d,{recursive:!0}),await uv(w,d,{recursive:!0,force:!1}),await en(G.join(d,"runtime"),{recursive:!0}),await uv(y,G.join(d,hv),{recursive:!0,force:!1})});let S=await pn({pmRoot:d,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${f.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:f.manifest.fingerprint,changed_file_count:_.changed_file_count,removed_file_count:_.removed_file_count,removed_item_count:_.removed_item_count,affected_history_stream_count:_.affected_history_stream_count,removed_history_entry_count:_.removed_history_entry_count},lockTtlSeconds:i,lockWaitMs:s}),A=G.relative(d,S.historyPath).replaceAll("\\","/");await c.stop(),u=!0;let v=fi(d,Un),T=d;return await o.fence(async()=>{await en(G.dirname(v),{recursive:!0}),await bo(v,await jn(fi(e,Un)),{flag:"wx"}),l=!0,await DD(T,e,C,gv,async()=>{c.start(),u=!1,await c.refreshNow()})}),await c.stop(),u=!0,{manifest:h,plan:_,recovery_fingerprint:f.manifest.fingerprint,audit_history_path:A,audit_operation:"workspace_snapshot_restore"}}catch(_){throw d!==void 0&&!l&&await Promise.allSettled([Dd(d,{recursive:!0,force:!0})]),_}finally{try{u||await c.stop()}catch{}finally{await a()}}}async function kV(e,t){return(await FD(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function EV(e,t){Nd(t);let n=tn(e);if(!/^[a-f0-9]{64}$/.test(t))return await pv(G.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await PD(e);if(r.some(i=>i.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await pv(G.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]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function Ev(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function Sv(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?W([...r,"merge","report"],n):e==="history_evidence_invalid"?W([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?W([...r,"merge","reconcile"],n):e==="history_repair_required"?W([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?W([...r,"merge","install"],n):null}function Tv(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(n=>typeof n=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(n=>typeof n=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function PV(e){let t=R(process.cwd(),e.path);await F(t);let n=await x(t),r=P(n,M()),i=[],s=await Ss({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await Tt(t),[a,c,d,l]=await Promise.all([wn(t,yn(n)),o===null?Promise.resolve(null):vn(o),bn(o??t,{includeLossless:!0,pmRoot:t}),Ts(t,s,!1)]),{pendingDecisions:u,lossless:_}=kn(d.receipts),h=[...new Set(u.map(w=>w.item_id))].sort((w,b)=>w.localeCompare(b)),f=l.check.details,g=Tv(f),y=Ev({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:_.length,historyEvidenceValid:g.evidence_valid,driftedItemCount:g.drifted_item_count,fence:a,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:h.slice(0,25),pending_item_ids_truncated:h.length>25,lossless_count:_.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:g,next_action:{command:Sv(y,t),reason:y},warnings:[...new Set(i)].sort((w,b)=>w.localeCompare(b)),generated_at:I()}}function $V(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
|
|
16
|
+
`)}var FV={commandForWorkspacePositionState:Sv,normalizeWorkspaceHistoryDrift:Tv,selectWorkspacePositionState:Ev};import{createHash as jD}from"node:crypto";import{execFile as GD}from"node:child_process";import xv from"node:path";import{promisify as qD}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Cv=1;function UD(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 Pd(e){if(e===null)return{format_version:Cv,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new p("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Cv||!Array.isArray(t.observations))throw new p("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!UD(r))throw new p("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var KD=qD(GD),WD=50,Av=1e3,zD=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Rv(e){let t=e.trim().toLowerCase();if(!zD.test(t))throw new p(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function BD(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new p("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function Br(e,t){let n=e?.trim();if(n){if(n.length>256)throw new p(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function HD(e){let t=e??WD;if(!Number.isSafeInteger(t)||t<0||t>Av)throw new p(`Improvement observation limit must be an integer from 0 to ${Av}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Iv(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new p(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function VD(e,t,n){if(!Number.isFinite(n.value))throw new p("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let r=Rv(n.metric),i=BD(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||i==="target"&&n.threshold===void 0)throw new p("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let s=await XD(e,n.revision),o=Br(n.source,"source"),a=Br(n.itemId,"itemId"),c=Br(n.unit,"unit"),d=Br(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,o??"manual",a??"workspace"].join(":")),l={metric:r,value:n.value,direction:i,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Iv(n.observedAt??I(),"observedAt"),...s,author:U(n.author,t.author_default),...a===void 0?{}:{item_id:a},...o===void 0?{}:{source:o},...d===void 0?{}:{idempotency_key:d}};return{id:jD("sha256").update(ne(l)).digest("hex").slice(0,24),...l}}function YD(e,t){let n=t.idempotency_key?e.observations.find(i=>i.idempotency_key===t.idempotency_key):e.observations.find(i=>i.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 p(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(i=>i.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new p(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function XD(e,t){let n=Br(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await KD("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Qe(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function JD(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,i=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:i,sample_count:e.length}}async function Ov(e,t={}){let n=R(process.cwd(),t.path);await F(n);let r=await x(n),i=await VD(n,r,e),s=xv.join(n,"improvement-ledger.json"),o=await _n({pmRoot:n,filePath:s,op:"improvement_observe",author:i.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${i.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Pd(a),d=YD(c,i);return d?{raw:a,result:d}:(c.observations.push(i),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${ne(c)}
|
|
17
|
+
`,result:i})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function Lv(e={}){let t=R(e.cwd??process.cwd(),e.pmRoot);await F(t);let n=e.metric===void 0?void 0:Rv(e.metric),r=e.since===void 0?void 0:Iv(e.since,"since"),i=HD(e.limit),s=Pd(await Z(xv.join(t,"improvement-ledger.json"))).observations.filter(a=>(n===void 0||a.metric===n)&&(e.itemId===void 0||a.item_id===e.itemId)&&(r===void 0||a.observed_at>=r)),o=new Map;for(let a of s){let c=o.get(a.metric)??[];c.push(a),o.set(a.metric,c)}return{observations:[...s].reverse().slice(0,i),total:s.length,truncated:s.length>i,trends:[...o].map(([,a])=>JD(a)).sort((a,c)=>a.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function QD(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 ZD(e,t,n){let r=t,i=new Set([e.id]);for(;r!==void 0&&!i.has(r.id);)i.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function eN(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,i)=>r.entries[0].ts.localeCompare(i.entries[0].ts)||r.id.localeCompare(i.id)),t.push(...n.map(r=>r.children))}}function Dv(e=nr,t=tr){return t.map(n=>{let r=e.filter(i=>((n==="model"?i.model_environment_keys:i.provenance_environment_keys?.[n])?.length??0)>0||i.provenance_resolvers?.[n]!==void 0).map(i=>i.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function o4(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let i=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};i.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?i.observed+=1:r.agent_provenance?.model===null?i.unavailable+=1:i.legacy_missing+=1,n.set(r.agent_harness,i)}return[...n.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=t&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness))}function Nv(e,t=tr,n=1){let r=new Map;for(let i of e)if(i.agent_harness)for(let s of t){let o=`${i.agent_harness}\0${s}`,a=r.get(o)??{harness:i.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=i.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(o,a)}return[...r.values()].map(i=>{let s=i.observed+i.unavailable;return{...i,coverage:s===0?null:i.observed/s,inert:s>=n&&i.observed===0}}).sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension))}function a4(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 i=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=i.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let _=c.agent_provenance?.[d];_?.value&&(u.observed+=1,u.by_source[_.source]=(u.by_source[_.source]??0)+1),i.set(l,u)}let s=[...i.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),o=s.filter(c=>c.entries>=r),a=o.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:o.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function c4(e){let t=[...e].sort((s,o)=>s.ts.localeCompare(o.ts)||s.author.localeCompare(o.author)||s.op.localeCompare(o.op)||s.before_hash.localeCompare(o.before_hash)||s.after_hash.localeCompare(o.after_hash)),n=new Map,r=new Map;for(let s of t){let o=s.agent_episode,a=QD(s),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[s],children:[]};n.set(c,l),o!==void 0&&r.set(a.id,l)}let i=[];for(let s of n.values()){let o=s.parent_id?r.get(s.parent_id):void 0;o&&ZD(s,o,r)?o.children.push(s):i.push(s)}return eN(i),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]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var tN=1e4,Mv=1e5,nN=1e3,rN=30,iN=["append","comment","docs","file","learning","note","test_run"];function sN(e){let t=e??tN;if(!Number.isSafeInteger(t)||t<1||t>Mv)throw new p(`History analytics event limit must be an integer from 1 to ${Mv}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Pv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function oN(e){let t=e?.trim();if(!t)return new Date(Date.now()-rN*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let i=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(i)||i<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-i*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function ko(e,t){let n=sN(t.eventLimit),r=oN(t.since),i=[],s=r,o=!1;for(;i.length<n;){let a=await sf({pmRoot:e,since:s,limit:Math.min(nN,n-i.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(i.push(...c),o=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:i,receipt:{since:r,events:i.length,truncated:o,...o?{next_cursor:s}:{},source:"history_event_index"}}}function aN(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function cN(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 dN(e){return iN.some(t=>e.startsWith(t))}function $v(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 lN(e,t,n){let r=new Map,i=new Map,s=new Map;for(let o of t){let a=aN(o.entry,e),c=cN(o.entry),d=i.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&i.set(o.item_id,l),!a)continue;let u=$v(r,a);u.events+=1,dN(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:s}}function uN(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let i=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of i){let o=t.get(s);o&&($v(e,o).defectEscapes+=1)}}}function mN(e,t,n,r){let i=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:i==="available"?t.closes/r:null,rework_rate:i==="available"?t.reopens/t.closes:null,defect_escape_rate:i==="available"?t.defectEscapes/t.closes:null,sample_status:i}}function pN(e,t,n,r,i,s){let{buckets:o,lastCloseValue:a}=lN(e,t,r);return uN(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>mN(c,d,i,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function _N(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,i=Date.parse(n),s=Date.parse(r);return!Number.isFinite(i)||!Number.isFinite(s)?1:Math.max(1,(s-i)/864e5)}function fN(e,t,n){let r=Dv(t),i=Nv(e,tr,n),s=i.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:i,inert:s,undeclared:o,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function f4(e,t=nr,n={}){return $d(await ko(e,n),t,n)}function $d(e,t=nr,n={}){let r=Pv(n.minimumSample);return{...fN(e.events.map(i=>i.entry),t,r),window:e.receipt}}async function h4(e,t,n,r={}){return Fd(await ko(e,r),t,n,r)}function Fd(e,t,n,r={}){let i=Pv(r.minimumSample),s=_N(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>pN(o,e.events,t,n,i,s)),minimum_sample:i,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var hN=32;function gN(e){let t=[];for(let n of e??[]){let r=[];for(let i of n.split(",")){let s=i.slice(0,i.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(i)}t.push(r.join(","))}return t}function Hr(e,t){let n=gN(e).map(r=>{let[i,...s]=r.split(","),o=i.indexOf("="),a=i.slice(0,o).trim(),c=i.slice(o+1).trim(),d=Number(c);if(o<=0||a.length===0||c.length===0||!Number.isFinite(d))throw new p(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let l,u;for(let _ of s){let h=_.indexOf("="),f=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(f==="unit"&&g.length>0)l=g;else if(f==="threshold"&&g.length>0&&Number.isFinite(Number(g)))u=Number(g);else throw new p(`Invalid --measure attribute "${_}"`,m.USAGE)}return{name:a,value:d,unit:l,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,i)=>r.name.localeCompare(i.name)).slice(0,hN)}function Fv(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(i=>i.name===t&&i.value<n).map(i=>({...i,run_id:r.run_id})))}function Uv(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,o)=>o.recorded_at.localeCompare(s.recorded_at)),r=n[0],i=n[1];return{name:t,latest:r?.value??null,previous:i?.value??null,delta:r!==void 0&&i!==void 0?r.value-i.value:null,unit:r?.unit}}import wN from"node:fs/promises";import Gv from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function Eo(e,t,n,r,i,s="min"){let o=i==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return o<0||o===0&&r!==null&&a<0}function yN(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,i=null,s=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,_=Date.parse(u);Number.isNaN(_)||(Eo(_,o,u,i,"min")&&(o=_,i=u),Eo(_,a,u,s,"max","max")&&(a=_,s=u))}return{id:e,bytes:n,lines:r,oldest_ts:i,newest_ts:s}}function jv(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),i=e.map(({id:h,raw:f})=>yN(h,f)),s=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let h of i){if(s+=h.lines,o+=h.bytes,h.oldest_ts!==null){let f=Date.parse(h.oldest_ts);Eo(f,d,h.id,a?.id??null,"min")&&(d=f,a={id:h.id,ts:h.oldest_ts})}if(h.newest_ts!==null){let f=Date.parse(h.newest_ts);Eo(f,l,h.id,c?.id??null,"max")&&(l=f,c={id:h.id,ts:h.newest_ts})}}let u=r===0?[]:[...i].sort((h,f)=>f.bytes-h.bytes||h.id.localeCompare(f.id)).slice(0,r),_=r===0?[]:[...i].sort((h,f)=>f.lines-h.lines||h.id.localeCompare(f.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:o,largest_by_bytes:u,deepest_by_lines:_,oldest_entry:a,newest_entry:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function vN(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function bN(e,t,n,r,i){let s=cr(e,"type",r),o=new Set(s.rows.map(u=>u.key)),a=t.filter(u=>!o.has(u)),c=(i?[...s.rows,...a.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),d=vN([...n]);for(let u of e)d[u.status]+=1;let l=Object.fromEntries(Object.entries(d).filter(([,u])=>i||u>0));return{byType:c,byStatus:l,omitted:i?0:a.length+Object.values(d).filter(u=>u===0).length}}function kN(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function EN(e){let t=Gv.join(e,"history");if(!await re(t))return[];await Ue({path:t,scope:"project"});let n=(await wN.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=Gv.join(t,i),o=await Z(s);o!==null&&(await Ue({path:s,scope:"project"}),r.push({id:i.slice(0,-6),raw:o}))}return r}async function SN(e,t){let n=[],r=I();for(let i of Hr(t.observe,r))n.push(await Ov({metric:i.name,value:i.value,direction:t.direction,unit:i.unit,threshold:i.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function TN(e,t,n){let r={};return t.byAssignee&&(r.assignee=cr(e,"assignee",n)),t.byTag&&(r.tag=cr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=cr(e,"priority",n)),r}async function CN(e,t,n,r,i){let s={since:i.since,eventLimit:i.eventLimit,minimumSample:i.minimumSample},o=i.provenanceCoverage||i.fleetAttribution?await ko(e,s):void 0;return{provenanceCoverage:i.provenanceCoverage&&o?$d(o,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:i.fleetAttribution&&o?Fd(o,t,r,s):void 0}}function AN(e,t,n,r,i){let s=Object.keys(i.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...i.metadataCoverage?{metadata_coverage:i.metadataCoverage}:{},...s?{breakdowns:i.breakdowns}:{},...i.storage?{storage:i.storage}:{},...i.fieldUtilization?{field_utilization:i.fieldUtilization}:{},...i.improvementLedger?{improvement_ledger:i.improvementLedger}:{},...i.recordedObservations.length>0?{recorded_observations:i.recordedObservations}:{},...i.provenanceCoverage?{provenance_coverage:i.provenanceCoverage}:{},...i.fleetAttribution?{fleet_attribution:i.fleetAttribution}:{},generated_at:I()}}async function U4(e,t={}){let n=R(process.cwd(),e.path);await F(n);let r=await x(n),i=await SN(e,t),s=P(r,M()),o=q(r.schema),a=t.fieldUtilization?await lt(n,r.item_format,s.type_to_folder,void 0,r.schema):await Ee(n,r.item_format,s.type_to_folder,void 0,r.schema);await Ii({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=D_(o),d=bN(a,s.types,o.definitions.map(k=>k.id),c,t.includeEmpty===!0),l=await EN(n),u=0;for(let k of l)u+=kN(k.raw);let _=t.storage?jv(l):void 0,h=t.metadataCoverage?N_(a,c):void 0,f=TN(a,t,c),g=t.fieldUtilization?M_(a):void 0,y=t.measurements===!0||i.length>0?await Lv({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:b}=await CN(n,a,r,o.terminal_statuses,t);return AN({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:h,breakdowns:f,storage:_,fieldUtilization:g,improvementLedger:y,recordedObservations:i,provenanceCoverage:w,fleetAttribution:b})}import xN from"node:fs/promises";import gt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a41eaff2-6a15-5e82-b3aa-03ca48fc3eb5")}catch{}})();var Bv=gt.join("runtime","telemetry","events.jsonl"),Gd=gt.join("runtime","telemetry","state.json"),RN=gt.join("runtime","telemetry"),IN=20,qd=Lt.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]},Ud=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Wv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},ON=e=>({command:Ud(e.event.command,"<unknown>"),eventType:Ud(e.event.event_type,"unknown"),eventSchemaVersion:Wv(e.event.schema_version),clientSchemaVersion:Wv(e.client_schema_version)}),LN=()=>({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:{}}),DN=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},NN=e=>{let t=e?.command_resolution;return Ud(t,"")||void 0},Hv=(e,t)=>{e[t]=(e[t]??0)+1},MN=(e,t)=>{let n=DN(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=NN(t);r!==void 0&&Hv(e.resolution_counts,r)},PN=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,zv=(e,t)=>{t!==void 0&&e.add(t)},$N=(e,t)=>{let n=ON(t),r=e.get(n.command)??LN();r.count+=1,r.max_attempts=Math.max(r.max_attempts,PN(t.attempts)),Hv(r.event_type_counts,n.eventType),zv(r.event_schema_versions,n.eventSchemaVersion),zv(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&MN(r,t.event.payload),e.set(n.command,r)},FN=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,o)=>s-o),i=Object.entries(t.resolution_counts).sort((s,o)=>s[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,o)=>s[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,o)=>s-o),client_schema_versions:[...t.client_schema_versions].sort((s,o)=>s-o),...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}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},UN=e=>{let t=(e??"status").trim().toLowerCase();if(qv.includes(t))return t;throw vi({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:qv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Kd=()=>{throw new p("--limit must be a positive integer",m.USAGE)},Vv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Kd():e,jN=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Kd():Vv(Number.parseInt(t,10))},GN=e=>e===void 0?IN:typeof e=="number"?Vv(e):typeof e=="string"?jN(e):Kd(),qN=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},KN=e=>{try{let t=JSON.parse(e);return qN(t)?t:void 0}catch{return}},WN=e=>e===null?[]:e.split(`
|
|
18
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),Yv=e=>{let t=WN(e),n=[],r=0;for(let i of t){let s=KN(i);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},zN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BN=e=>{try{let t=JSON.parse(e);return zN(t)?t:{}}catch{return{}}},To=async e=>{let t=await Z(e);return t===null||t.trim().length===0?{}:BN(t)};function Xv(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 HN(e,t,n){let r=Object.create(null);for(let[i,s]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(i)||i<t||i>n||typeof s!="object"||s===null||Array.isArray(s))continue;let o=s;!Number.isSafeInteger(o.count)||o.count<1||typeof o.last_seen!="string"||!o.last_seen.startsWith(i)||(r[i]={count:o.count,last_seen:o.last_seen})}return r}function jd(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,i=new Date().toISOString().slice(0,10);for(let s of qd){let o=r[s.alias];if(typeof o!="object"||o===null||Array.isArray(o))continue;let a=o;if(a.canonical!==s.canonical||typeof a.days!="object"||a.days===null||Array.isArray(a.days))continue;let c=HN(a.days,t,i);Object.keys(c).length>0&&(n[s.alias]={canonical:s.canonical,days:c})}return n}async function VN(e,t,n){let r=Xv(n),i=await To(t),s=jd(i.alias_usage,r);if(JSON.stringify(i.alias_usage??{})===JSON.stringify(s))return s;try{await Ui(async()=>{let o=await To(t);if(o.alias_usage===void 0)return;let a=jd(o.alias_usage,r);JSON.stringify(o.alias_usage)!==JSON.stringify(a)&&await Le(t,`${JSON.stringify({...o,alias_usage:a},null,2)}
|
|
19
|
+
`)},e,250)}catch{}return s}async function Z4(e){let t=qd.find(r=>r.alias===e);if(!t||Ft().telemetry_disabled)return!1;let n=qe(process.cwd());try{return await Ui(async()=>{let r=await x(n);if(!r.telemetry.enabled||Ft().telemetry_disabled)return!1;let i=gt.join(n,Gd),s=await To(i),o=jd(s.alias_usage,Xv(r.telemetry.retention_days)),a=new Date().toISOString().slice(0,10),c=o[e]?.days[a];return o[e]={canonical:t.canonical,days:{...o[e]?.days,[a]:{count:Math.min(Number.MAX_SAFE_INTEGER,(c?.count??0)+1),last_seen:I()}}},await Le(i,`${JSON.stringify({...s,alias_usage:o},null,2)}
|
|
20
|
+
`),!0},n,250)}catch{return!1}}var So=e=>e??null,Co=async e=>{let t=await x(e),n=gt.join(e,Bv),r=gt.join(e,Gd),i=await Z(n),s=Yv(i),o=await To(r),a=Ft();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:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:So(o.last_attempted_flush_at),last_successful_flush_at:So(o.last_successful_flush_at),last_failed_flush_at:So(o.last_failed_flush_at),last_failed_flush_error:So(o.last_failed_flush_error)}},YN=e=>{let t=new Map;for(let n of e)$N(t,n);return[...t.entries()].map(([n,r])=>FN(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},XN=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Co(t.globalPmRoot),generated_at:I()}),JN=async(e,t)=>{let n=await Co(t.globalPmRoot);await Nm(t.globalPmRoot);let r=await Co(t.globalPmRoot),i=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:s,queue_drained:s,status:r,generated_at:I()}},QN=async(e,t)=>{let n=GN(e.limit),r=await Z(t.queuePath),i=Yv(r),s=YN(i.entries),o=s.slice(0,n),a=await x(t.globalPmRoot),c=await VN(t.globalPmRoot,t.statePath,a.telemetry.retention_days),d=Object.entries(c).map(([l,u])=>{let _=Object.values(u.days);return{alias:l,canonical:u.canonical,count:_.reduce((h,f)=>Math.min(Number.MAX_SAFE_INTEGER,h+f.count),0),last_seen:_.map(h=>h.last_seen).sort().at(-1)}}).sort((l,u)=>u.count-l.count||l.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:s.length>o.length,stats:o,alias_usage:d,zero_use_aliases:qd.map(l=>l.alias).filter(l=>c[l]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:I()}},ZN=async(e,t)=>Ui(async()=>{let n=await x(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 mm(t.globalPmRoot,n,"telemetry:clear");let i=gt.join(t.globalPmRoot,RN),s=await re(i);return await xN.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await re(i),queue_exists_after:await re(t.queuePath),state_exists_after:await re(t.statePath),status:await Co(t.globalPmRoot),generated_at:I()}},t.globalPmRoot),eM={status:XN,flush:JN,stats:QN,clear:ZN};async function e5(e,t){let n=UN(e.subcommand),r=qe(process.cwd());return eM[n](e,{globalPmRoot:r,queuePath:gt.join(r,Bv),statePath:gt.join(r,Gd)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var Jv=100;function Gn(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new p(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function tM(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=Jv?t:`${t.slice(0,Jv-3)}...`}function Qv(e){return e.map((t,n)=>`${n+1}. ${tM(t)}`).join("; ")}function nM(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 rM(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Zv(e,t){let n=nM(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new p(`Combine at most one linked-test selector per run: ${n.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let r=n[0];if(e.length===0)throw new p(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let i=t.match.trim().toLowerCase();if(i.length===0)throw new p("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let s=[],o=[];for(let a=0;a<e.length;a+=1)rM(e[a],i)&&(o.push(e[a]),s.push(a+1));if(o.length===0)throw new p(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Qv(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:s,selected_count:o.length,skipped_count:e.length-o.length}}if(r==="only-index"){let i=Gn(t.onlyIndex);if(i>e.length)throw new p(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${Qv(e)}`,m.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],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]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();var Wd=["command","cmd"],Vr=Object.freeze(at.filter(e=>!["command","cmd","timeout"].includes(e)));function eb(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new p("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new p("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:Gn(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function tb(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new p("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function iM(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new p("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=Gn(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",i="command"in t?t.command:t.path;if(typeof i!="string"||i.trim().length===0)throw new p("Linked-test selector must be a non-empty command or path",m.USAGE);let s=e.flatMap((o,a)=>o[r]===i?[a]:[]);if(s.length===1)return s[0];if(s.length>1)throw new p(`Linked-test selector is ambiguous; matching indexes: ${s.map(o=>o+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new p("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function nb(e,t){let n=Object.keys(e),r=n.filter(i=>!Vr.includes(i));if(n.length===0&&!t||r.length>0)throw new p("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${Vr.join(", ")}.`,recovery:{allowed_values:[...Vr]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new p("scope is required and cannot be cleared",m.USAGE)}function sM(e,t,n){let r={};for(let i of Vr){let s=t[i]!==void 0?t[i]:e[i];s!=null&&(r[i]=s)}return{command:n,...r}}function Ao(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function oM(e,t,n){let r=Wd.filter(s=>Object.hasOwn(e,s)).map(s=>e[s]),i=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(s=>typeof s!="string"||s.trim()!==i))throw new p("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...Ao(t),nextSteps:["Send the replacement command once, as command."]});if(i.length===0||i===n.command)throw new p(i.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,m.USAGE,{code:"linked_test_command_immutable",...Ao(t),nextSteps:[`Patch only editable fields: ${Vr.join(", ")}.`]});return Ir(i),i}function aM(e){let{id:t,tests:n,index:r,identityKey:i,otherFields:s,requested:o,global:a}=e;nb(s,!0);let c=sM(n[r],s,o),d=jr(JSON.stringify(c),"--add-json")[0];Jn(d);let l=n.findIndex((u,_)=>_!==r&&hi(u,d));if(l>=0)throw new p(`--set-json cannot change ${i}: linked test ${l+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...Ao(i),nextSteps:[`Edit linked test ${l+1} instead: ${W([...dn(a),"test",t,"--update-index",String(l+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${W([...dn(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function cM(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function dM(e){let{id:t,tests:n,index:r,patch:i,global:s,controls:o}=e;if(typeof i!="object"||i===null||Array.isArray(i))return;let a=i,c=Wd.find(g=>Object.hasOwn(a,g));if(c===void 0)return;let d=n[r],l=oM(a,c,d),u=Object.fromEntries(Object.entries(a).filter(([g])=>!Wd.includes(g))),_=aM({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:l,global:s}),h=d.command!==void 0&&n.filter(g=>g.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],f=[...dn(s),"test",t,...h,"--add-json",JSON.stringify(_),...cM(o)];throw new p(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,m.USAGE,{code:"linked_test_command_immutable",...Ao(c),recovery:{suggested_retry:W(f),suggested_retry_args:f},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${h[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function lM(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);nb(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>at.includes(a))),i=Lu(jr(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);Jn(i);let s=n.filter(a=>!$e(e[a],i[a])),o={...e};for(let a of s){let c=i[a];Object.assign(o,{[a]:c}),c===void 0&&delete o[a]}if(!o.command?.trim()&&!o.path?.trim())throw new p("Linked-test entry must retain a command or path",m.USAGE);return{test:o,fields:s}}async function rb(e,t,n={}){let r=R(process.cwd(),n.path);await F(r);let i=await x(r),s=U(t.author,i.author_default),o=P(i,M()),a=0,c=[],d=await hn({pmRoot:r,settings:i,id:e,author:s,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:o.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(u){let _=u.metadata.tests??[],h=iM(_,t.selector);dM({id:u.metadata.id,tests:_,index:h,patch:t.patch,global:n,controls:t});let f=lM(_[h],t.patch);return a=h+1,c=f.fields,f.fields.length===0?{changedFields:[]}:(u.metadata.tests=_.map((g,y)=>y===h?{...f.test,updated_by:s,updated_at:I()}:g),{changedFields:["tests"]})}}),l=d.item.tests;return{ok:!0,id:d.item.id,tests:l,count:l.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="626315a0-7ee9-500d-bb7a-9bcd33eae209")}catch{}})();var uM=[{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_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{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}],mM=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function xo(e,t){let n=`${e}
|
|
21
|
+
${t}`;for(let r of uM)if(r.regex.test(n))return{code:r.code};return null}function ib(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let i=mM.find(s=>s.regex.test(r));if(i)return{code:i.receiptCode,stream:n}}}function sb(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function ob(e,t={}){let n=t.trackerPath?.trim();return W(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5aa7e990-08d9-56e4-860c-3fc52cebe728")}catch{}})();function ab(e,t,n,r,i){if((t.measure?.length??0)===0||i.some(o=>typeof o.stdout=="string"&&o.failure_category!=="spawn_error"&&o.failure_category!=="empty_run"&&xo(o.stdout,o.stderr??"")===null))return;let s=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new p("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:W(s),suggested_retry_args:s}})}function zd(e,t,n,r,i=!1){if((t.measure?.length??0)===0||t.run===!0)return;let s=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],o=[...s,...O_(e,t),...t.list?["--list"]:[],...i?["--background"]:[]],a=t.acknowledgeLinkedTests?[...s,"test",e,"--help"]:o,c=[...s,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new p("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${W([...s,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${W(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${W(o)}`]}:{},recovery:{missing:["--run"],suggested_retry:W(a),suggested_retry_args:a}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function cb(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 i=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(i))return[];t.push(i);continue}t.push(r)}return t}function Bd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=cb(n);if(r.length===0)return{found:!1,value:void 0};let i=e;for(let s of r){if(typeof i!="object"||i===null)return{found:!1,value:void 0};if(typeof s=="number"&&(!Array.isArray(i)||s>=i.length))return{found:!1,value:void 0};let o=Object.getOwnPropertyDescriptor(i,s);if(!o||!Object.hasOwn(o,"value"))return{found:!1,value:void 0};i=o.value}return{found:!0,value:i}}import{cp as yM,lstat as wM,mkdir as vM,readlink as bM,realpath as Yd,stat as kM,symlink as ub}from"node:fs/promises";import{execFile as EM}from"node:child_process";import B from"node:path";import{promisify as SM}from"node:util";import{execFile as pM}from"node:child_process";import{readdir as _M,realpath as fM}from"node:fs/promises";import hM from"node:path";import{promisify as gM}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]="e67d1a06-77f7-5e86-8f15-bde8b6db0d5a")}catch{}})();var Hd=gM(pM),db=".agents/pm/merge-receipts";async function lb(e,t,n){let r=hM.join(n,"merge-receipts"),i=(await _M(r).catch(c=>{if(j(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:s}=await import("./indexed-receipt-blobs-I6RQGD6Y.js"),o=i.length===0?new Map:await s(e,r,i,K_,await fM(r),{failOnReadError:!0}),a={cwd:t,env:q_(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await Hd("git",["rm","-q","-r","--cached","--ignore-unmatch","--",db],a);for(let[c,d]of o){let l=Hd("git",["hash-object","-w","--stdin"],a),u=l.child.stdin;u!==null&&(u.on("error",()=>{l.child.kill()}),u.end(d));let _=(await l).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(_))throw new Error("Invalid snapshot receipt object identity.");await Hd("git",["update-index","--add","--cacheinfo","100644",_,`${db}/${c}`],a)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6638f21c-6cf5-5dec-a0d9-91ae323afce3")}catch{}})();var TM=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),Ro=SM(EM);async function CM(e,t){let n=await Io(B.join(e,".git"));if(!n||n.isDirectory()&&!await Io(B.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([i])=>!i.toUpperCase().startsWith("GIT_")));await Ro("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await Ro("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await Ro("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(i){if(i.code===1)return!0;throw i}return await Ro("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function AM(e,t,n,r){await CM(e,t)&&n&&r!==!1&&await lb(e,t,n)}function Vd(e){return e.split(B.sep).some(t=>TM.has(t.toLowerCase()))}function Yr(e){return e===".."||e.startsWith(`..${B.sep}`)||B.isAbsolute(e)}async function Io(e){try{return await kM(e)}catch(t){if(!j(t))throw t;return}}async function Oo(e){let t=[],n=e;for(;B.dirname(n)!==n;)try{return B.join(await Yd(n),...t)}catch(r){if(!j(r))throw r;t.unshift(B.basename(n)),n=B.dirname(n)}return B.join(await Yd(n),...t)}async function xM(e,t,n){let r=B.relative(t,await Oo(e));if(!Yr(r))return r;let i=[],s=e;for(;B.dirname(s)!==s;){let o=await Oo(s),a=n.find(([,c])=>c===o);if(a)return B.join(a[0],...i);i.unshift(B.basename(s)),s=B.dirname(s)}return r}async function mb(e,t,n,r){let i=[],s=[],o=await Yd(e),a=await Oo(B.resolve(t));if(![B.relative(o,a),B.relative(a,o)].every(Yr))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await vM(B.dirname(t),{recursive:!0}),await AM(o,t,n,r),await yM(o,t,{recursive:!0,force:!0,async filter(c){let d=B.relative(o,c);if(!d)return!0;if(Vd(d))return!1;if(B.basename(c).toLowerCase()==="node_modules"){if((await Io(c))?.isDirectory()){let l=await Oo(c),u=B.relative(o,l);if(!Yr(B.relative(l,o))||!Yr(u)&&(Vd(u)||!u.split(B.sep).some(_=>_.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${d}`);i.push([d,l])}return!1}return(await wM(c)).isSymbolicLink()?(s.push([d,B.resolve(B.dirname(c),await bM(c)),(await Io(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of i)await ub(B.resolve(o,c),B.join(t,c),"junction");for(let[c,d,l]of s){let u=await xM(d,o,i);if(Yr(u)||Vd(u))throw new Error(`Source symlink must target included workspace source: ${c}`);await ub(B.resolve(t,u),B.join(t,c),l)}}import{execFile as RM}from"node:child_process";import{constants as pb}from"node:fs";import{access as IM,open as OM}from"node:fs/promises";import _b from"node:path";import{promisify as LM}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]="b42f8889-4b5a-5391-b8e4-b68084e20a49")}catch{}})();var DM=LM(RM);function NM(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function MM(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function PM(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await OM(_b.resolve(t,n),pb.O_RDONLY|pb.O_NONBLOCK),i;try{let o=Buffer.alloc(256),{bytesRead:a}=await r.read(o,0,o.length,0);if(i=o.toString("utf8",0,a),a===o.length&&!i.includes(`
|
|
22
|
+
`))return!1}finally{await r.close()}let s=i.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!s)return!1;try{return await IM(s),!1}catch(o){return an(o)}}catch{return!1}}async function fb(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let i=NM(e);if(!i||!MM(i,t.exitCode,t.stderr))return!1;let s=process.platform==="win32",o=s?_b.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",a=s?[i]:["-c",'command -v "$1"',"pm-linked-test-resolution",i];try{let{stdout:c}=await DM(o,a,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!s&&PM(c,r)}catch(c){let d=c;if(d.killed||d.signal)return!1;let l=d.code;return l===1||!s&&l===127}}import{spawn as Db}from"node:child_process";import{cp as gb,mkdir as el,mkdtemp as Nb,open as Jd,readdir as Qd,rm as Jr,symlink as FM}from"node:fs/promises";import{tmpdir as Mb}from"node:os";import ae from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var hb=20;function $M(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return hb;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?hb:t}function Xd(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,i)=>{let s=wi(r.recorded_at,i.recorded_at);if(s!==0)return s;let o=r.run_id.localeCompare(i.run_id);return o!==0?o:r.kind.localeCompare(i.kind)}),n=$M();return t.length>n?t.slice(t.length-n):t}async function Lo(e){await me({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=Xd([...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]="0ba78f5c-3dbc-50eb-b6a4-df29b4d9b251")}catch{}})();var Mo=20*1024*1024,UM=3e3,jM=1e4,GM=5e3,yb=120,qM=new Set(["locks","extensions","runtime"]),KM=new Set(["history","index","search","extensions","locks","runtime"]),WM=[/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],zM=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,BM=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,HM=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 tl(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 VM(){return tl("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",UM)}function YM(){return tl("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",jM)}function XM(){return tl("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",GM)}function JM(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 QM(e){let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function nl(e){let t=0,n=0,r=0,i=0;for(let s of e){let o=s.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(r+=1),o.auto_pm_context_applied===!0&&(i+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:i}}function ZM(e){let t=e??"project";if(!Fe.includes(t))throw new p(`Invalid scope "${e}"`,m.USAGE);return t}function $o(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Ht.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${Ht.join(", ")}`,m.USAGE)}function Pb(e){return Yt(e??"source","--workspace-context")}function $b(e,t,n){return n?t:Yt(e.workspace_context_mode,"linked test")??t}function Fb(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:$o(e.pm_context_mode)}function Ub(e,t){return e==="auto"?t?"tracker":"schema":e}function eP(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 tP(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 nP(e,t){let n={};if(!e)return n;for(let r of e){let i=Fr(r,t);if(i)for(let[s,o]of Object.entries(i))n[s]=o}return n}function rP(e,t){if(!e)return[];let n=[];for(let r of e){let i=Ur(r,t);i&&n.push(...i)}return[...new Set(n)]}function iP(e){let t=Ln(e);return Kt(t).some(n=>vs(n)!==null)}function jb(e){let t=Ln(e);return Kt(t).some(n=>{let r=vs(n);if(!r)return!1;let i=Oc(r);return i?HM.has(i.subcommand):!1})}function Do(e){if(e)return Ug.has(e.subcommand)?At(e.args,jg)?.subcommand:e.subcommand}function wb(e,t){if(e==="npx"||e==="bunx")return Wt(t)?.command;if(e==="pnpm")return Do(At(t,xc));if(e==="npm")return Do(At(t,Rc));if(e==="yarn")return Do(At(t,$g));if(e==="bun")return Do(At(t,Fg))}function No(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function vb(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function rl(e){let t=e.split(" ").filter(o=>o.length>0),n=bs(t);if(n.length===0)return!1;let[r,...i]=n,s=Lc.get(r);if(s){let o=i.findIndex(a=>s.test(a));return o>=0&&rl(i.slice(o+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?sP(i):oP(r,i)}function sP(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function oP(e,t){return e==="npx"||e==="bunx"?No(Wt(t)?.command):e==="pnpm"||e==="npm"?No((e==="pnpm"?ks(t):Es(t))?.command)||No(wb(e,t)):(e==="yarn"||e==="bun")&&No(wb(e,t))}function G3(e){let t=Ln(e),n=Kt(t),r=n.some(s=>!vb(s)&&rl(s)),i=n.some(vb);return{accepted:!0,command_kind:r?"direct_runner":i?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:r?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function aP(e){if(Nc(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function cP(e){return e?e.map(dP):[]}function dP(e){let t=e.trim(),n=du(t)?gi(Q(e,"--add"),"--add"):{command:t},r=ye(n.command);if(!r)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return Ir(r),{command:r,path:ye(n.path),scope:ZM(n.scope),timeout_seconds:lP(ye(n.timeout_seconds),ye(n.timeout)),pm_context_mode:Ks(ye(n.pm_context_mode),"--add"),workspace_context_mode:Yt(ye(n.workspace_context_mode),"--add"),env_set:Fr(ye(n.env_set),"--add"),env_clear:Ur(ye(n.env_clear),"--add"),shared_host_safe:qs(ye(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Xt(ye(n.assert_stdout_contains)),assert_stdout_regex:Pn(ye(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Xt(ye(n.assert_stderr_contains)),assert_stderr_regex:Pn(ye(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ws(ye(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:zs(ye(n.assert_json_field_equals),"--add"),assert_json_field_gte:Bs(ye(n.assert_json_field_gte),"--add"),note:ye(n.note)}}function ye(e){let t=e?.trim();return t&&t.length>0?t:void 0}function lP(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ge(n,"timeout_seconds"));if(r<=0)throw new p("--add timeout_seconds must be a positive integer",m.USAGE);return r}function uP(e){return e?e.flatMap(t=>{let n=jr(t,"--add-json");for(let r of n){let i=r.command;if(!i)throw new p("--add-json requires a non-empty command string",m.USAGE);Ir(i)}return n}):[]}function mP(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new p("--remove requires command or path value",m.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let i=n.slice(r[0].length).trim();if(!i)throw new p("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:r[1].toLowerCase(),value:i}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let i=Q(n,"--remove"),s=i.path!==void 0?"path":"command",o=i.path??i.command;if(!o?.trim())throw new p("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:s,value:o.trim()}}return{kind:"either",value:n}}):[]}function pP(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 p("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function _P(e){try{e.stdin?.end()}catch{}}function Gb(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=yb?t:`${t.slice(0,yb-3)}...`}function qb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Zd(e){try{process.stderr.write(`${e}
|
|
23
|
+
`)}catch{}}function fP(e,t){if(!qb(t))return null;let n=Gb(e.command),r=Date.now();Zd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let i=setInterval(()=>{let s=Date.now()-r;Zd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},YM());return i.unref?.(),i}function hP(e,t,n,r){if(!qb(r))return;let i=Gb(e.command),s=Date.now()-n,o=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",a=[];t.timedOut&&a.push("reason=timeout"),t.maxBufferExceeded&&a.push("reason=max_buffer"),t.outputTruncated&&a.push("output=truncated"),t.signal&&a.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),d=a.length>0?` ${a.join(" ")}`:"";Zd(`[pm test] linked-test ${e.index}/${e.total} end status=${o} exit_code=${c} elapsed_ms=${s}${d} command="${i}"`)}async function bb(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Db("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 gP(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function yP(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 bb(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{bb(r)},VM()),t.forceKillTimer.unref?.()}}function wP(e){return new Promise(t=>{let n=!1,r=null,i=(s,o=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),o&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,o)=>{n||(r=setTimeout(()=>{i({code:s,signal:o},!0)},XM()),r.unref?.())}),e.on("close",(s,o)=>{i({code:s,signal:o})})})}function vP(e,t,n,r,i){return Db(e,{cwd:i,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function kb(e){let t=await Jd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Mo),i=Buffer.alloc(r);return r>0&&await t.read(i,0,r,0),{text:i.toString("utf8"),truncated:n>Mo}}finally{await t.close()}}async function bP(e,t,n,r,i,s=process.cwd()){let o=Date.now(),a=await Nb(ae.join(Mb(),"pm-linked-test-output-"));try{let c=ae.join(a,"stdout.log"),d=ae.join(a,"stderr.log"),[l,u]=await Promise.all([Jd(c,"w"),Jd(d,"w")]),_;try{_=vP(e,n,l.fd,u.fd,s)}catch(L){throw await Promise.all([l.close(),u.close()]),L}let h=wP(_),f;_.on("error",L=>{f=L.message}),await Promise.all([l.close(),u.close()]),_P(_);let g={heartbeat:fP(r,i),forceKillTimer:null,timedOutTimer:null},y=yP(_,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:b,signal:k}=await h;gP(g);let[C,S]=await Promise.all([kb(c),kb(d)]),A=C.truncated||S.truncated,v=A?`
|
|
24
|
+
[pm linked-test output truncated at ${Mo} bytes per stream; the child process continued to completion]
|
|
25
|
+
`:"";!f&&await fb(e,{exitCode:b,stderr:S.text},n,s)&&(f="Linked test executable was not found. Install the tool or update the linked command before retrying.");let T={stdout:`${C.text}${v}`,stderr:S.text,exitCode:b,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:A,spawnError:f};return hP(r,T,o,i),T}finally{await Jr(a,{recursive:!0,force:!0})}}function kP(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Mo} 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,i=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?i:`${i} ${n.join(" ")}`}function EP(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
26
|
+
`);return WM.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>zM.test(n)&&BM.test(n))}function SP(e){return EP(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function TP(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Qr(e){let t=TP();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}function Eb(e,t){for(let[n,r]of Object.entries(t.env_set))Vt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Vt.has(n.toUpperCase())||delete e[n]}function CP(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 AP(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],i=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:i}}function Kb(e,t,n){return{env_set:nP(e,"--env-set"),env_clear:rP(t,"--env-clear"),shared_host_safe:n===!0}}async function Xr(e,t,n=!1,r=el){if(await re(e))try{await Zn("seed_linked_test",async()=>{if(await r(ae.dirname(t),{recursive:!0}),n){await gb(e,t,{recursive:!0,force:!0});return}await gb(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(i){if(typeof i=="object"&&i!==null&&"code"in i&&j(i))return;throw i}}async function Sb(e,t,n,r=!1){for(let[i,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let o=await Z(Te(i));if(o!==null){let a=await x(s);await da({pmRoot:s,filePath:Te(s),raw:o,op:"settings:write",author:U(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Xr(Te(i),Te(s));await Xr(ae.join(n.projectPmRoot,"extensions"),ae.join(e,"extensions"),!0),await Xr(ae.join(n.globalPmRoot,"extensions"),ae.join(t,"extensions"),!0)}async function Tb(e,t){if(!await re(e))return;let n=await Qd(e,{withFileTypes:!0});for(let r of n){if(qM.has(r.name))continue;let i=ae.join(e,r.name),s=ae.join(t,r.name);if(r.isDirectory()){await Xr(i,s,!0);continue}r.isFile()&&await Xr(i,s)}}async function Cb(e,t){let n=await Z(Te(e));if(n===null||await re(rr(e)))return;let r=await x(t);await Jr(rr(t),{force:!0}),await Jr(Te(t),{force:!0}),await da({pmRoot:t,filePath:Te(t),raw:n,op:"settings:write",author:U(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 qn(e){if(!await re(e))return 0;let t=0,n=await Qd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||KM.has(r.name))continue;let i=ae.join(e,r.name),s;try{s=await Qd(i,{withFileTypes:!0})}catch{continue}for(let o of s)o.isFile()&&Nt.some(a=>o.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function xP(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function RP(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 IP(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?$e(e,t):Object.is(e,t)}function OP(e,t,n){let r=[];r.push(...Ab("stdout",t,e.assert_stdout_contains)),r.push(...xb("stdout",t,e.assert_stdout_regex)),r.push(...Ab("stderr",n,e.assert_stderr_contains)),r.push(...xb("stderr",n,e.assert_stderr_regex)),r.push(...LP(t,e.assert_stdout_min_lines));let i=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(i).length>0||Object.keys(s).length>0))return r;let o;try{o=JSON.parse(t)}catch(a){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${a instanceof Error?a.message:String(a)}`),r}for(let[a,c]of Object.entries(i)){let d=Bd(o,a);if(!d.found){r.push(`assert_json_field_equals missing path "${a}"`);continue}let l=RP(c);IP(d.value,l)||r.push(`assert_json_field_equals mismatch at "${a}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(d.value)})`)}for(let[a,c]of Object.entries(s)){let d=Bd(o,a);if(!d.found){r.push(`assert_json_field_gte missing path "${a}"`);continue}if(typeof d.value!="number"||!Number.isFinite(d.value)){r.push(`assert_json_field_gte path "${a}" resolved to non-numeric value`);continue}d.value<c&&r.push(`assert_json_field_gte failed at "${a}" (expected >= ${c}, actual ${d.value})`)}return r}function Ab(e,t,n){let r=[];for(let i of n??[])t.includes(i)||r.push(`${e} missing required text: "${i}"`);return r}function xb(e,t,n){let r=[];for(let i of n??[])try{new RegExp(i,"m").test(t)||r.push(`${e} failed regex assertion: /${i}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${i}/ (${s instanceof Error?s.message:String(s)})`)}return r}function LP(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}`]:[]}function Rb(e){let t=Ln(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Kt(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&rl(n))}function DP(e){return{root:e,schemaProjectPmPath:ae.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:ae.join(e,"schema","global"),trackerProjectPmPath:ae.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:ae.join(e,"tracker","global"),workspaceSnapshotRoot:ae.join(e,"workspace","project"),workspaceIsolatedRoot:ae.join(e,"workspace","isolated")}}function NP(e,t,n){return e.some(r=>$b(r,t,n)==="snapshot")}async function MP(e,t){let n=ae.join(e,".agents"),r=ae.join(n,"pm");await el(n,{recursive:!0}),await Jr(r,{recursive:!0,force:!0}),await FM(t,r,process.platform==="win32"?"junction":"dir")}async function PP(e,t=Ma,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 $P(e,t,n){t&&(await Sb(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await Sb(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Tb(t.projectPmRoot,e.trackerProjectPmPath),await Tb(t.globalPmRoot,e.trackerGlobalPmPath),await Cb(t.projectPmRoot,e.trackerProjectPmPath),await Cb(t.globalPmRoot,e.trackerGlobalPmPath)))}function FP(e,t,n){return e.some(r=>{let i=r.command??"",s=i.length>0&&jb(i),o=n?.autoPmContext===!0&&s?"auto":Fb(r,t,n?.overrideLinkedPmContext===!0);return Ub(o,s)==="tracker"})}async function UP(e,t){return{sourceProjectItemCount:t?await qn(t.projectPmRoot):0,sourceGlobalItemCount:t?await qn(t.globalPmRoot):0,schemaProjectItemCount:await qn(e.schemaProjectPmPath),schemaGlobalItemCount:await qn(e.schemaGlobalPmPath),trackerProjectItemCount:await qn(e.trackerProjectPmPath),trackerGlobalItemCount:await qn(e.trackerGlobalPmPath)}}function jP(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,i=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,o=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":o;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:i,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==i||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:o,source_workspace_root:a,trust:e.trust}}async function GP(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?$o(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?iP(n):!1,i=r&&n?jb(n):!1,s=e.options?.autoPmContext===!0&&i,o=s?"auto":Fb(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Ub(o,i),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await MP(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Fc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Fc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:jP({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:i,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function Ib(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function qP(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 KP(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 WP(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 KP(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 zP(e){if(!e.linkedTest.command)return Ib(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=aP(e.linkedTest.command);return t?Ib(e.linkedTest,e.executionContext,t):null}function BP(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Po(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?Po(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 Po(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function HP(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=tP({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Po(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function VP(e){return zP(e)||WP(e)||BP(e)||HP(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!eP(e.linkedTest)?Po(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function YP(e){let t=AP(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Eb(n,e.runtimeDirectives),Eb(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&CP(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!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[ur]):(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[ur]="read_only"),n}function XP(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function Ob(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 JP(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:xP(e.execution),failure_category:SP(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:kP(e.execution,e.timeoutMs)}}function QP(e){let t=ib(e.execution.stdout,e.execution.stderr);if(e.options?.failOnEmptyTestRun===!0||Rb(e.linkedTest.command??"")){let r=xo(e.execution.stdout,e.execution.stderr);if(r)return Ob({...e,emptyRunSignal:r});if(Rb(e.linkedTest.command??"")&&!t)return Ob({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let n=OP(e.linkedTest,e.execution.stdout,e.execution.stderr);return n.length>0?qP(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${n.join("; ")}`,e.execution):XP(e.linkedTest,e.executionContext,e.execution,t)}async function ZP(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await bP(t,n,YP(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?QP({...e,execution:r}):JP({...e,execution:r,timeoutMs:n})}async function il(e,t,n){for(let g of e)Xn(g.command);let r=[],i=await Nb(ae.join(Mb(),"pm-linked-test-")),s=DP(i),o=$o(n?.pmContext),a=Pb(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=Kb(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,u=Dr(),_=FP(e,o,n),h=NP(e,a,n?.overrideLinkedWorkspaceContext===!0),f=await Lr(u);try{await PP(s,Ma,_),await el(s.workspaceIsolatedRoot,{recursive:!0}),await $P(s,l,_),h&&await mb(u,s.workspaceSnapshotRoot,l?.projectPmRoot,_);let g=await UP(s,l);for(let y=0;y<e.length;y+=1){let w=e[y],b=$b(w,a,n?.overrideLinkedWorkspaceContext===!0),k=await GP({linkedTest:w,layout:s,counts:g,sourceRoots:l,runLevelPmContextMode:o,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:b,currentSourceRef:f,sourceWorkspaceRoot:u}),C=VP({linkedTest:w,executionContext:k.executionContext,runLevelPmContextMode:o,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(C){r.push(C);continue}r.push(await ZP({linkedTest:w,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Jr(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function e$(e){let{id:t,pmRoot:n,settings:r,typeToFolder:i}=e,s=await V(n,t,r.id_prefix,r.item_format,i);if(!s)throw new p(`Item ${t} not found`,m.NOT_FOUND);let o=await ue(s,{schema:r.schema});return{itemId:s.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1,removed:0}}function t$(e,t){let n=[...e];for(let r of t)n.some(i=>hi(i,r))||n.push(r);return n}function n$(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),i=e.filter((s,o)=>r.has(o+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:i,removed:e.length-i.length}}function r$(e,t,n,r){return n$(t$(e,t),n,r)}function i$(e){return[e.timeout!==void 0,e.progress===!0,(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 Wb(e){if(i$(e)&&e.run!==!0)throw new p("--timeout, --progress, --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",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new p("--match, --only-index, and --only-last require --run",m.USAGE)}async function s$(e){let{id:t,options:n,pmRoot:r,settings:i,typeToFolder:s,adds:o,removes:a,removeIndexes:c}=e;if(o.length===0&&a.length===0&&c.length===0)return e$({id:t,pmRoot:r,settings:i,typeToFolder:s});let d=0,l=await me({pmRoot:r,settings:i,id:t,op:o.length>0?"tests_add":"tests_remove",author:U(n.author,i.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let _=u.metadata.tests??[],h=r$(_,o,a,c);if(ra(()=>zb(n,h.tests)),d=h.removed,(a.length>0||c.length>0)&&d===0)throw new p("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(f=>`${f.kind}=${f.value}`),...c.map(f=>`index=${f}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=h.tests,{changedFields:$e(_,h.tests)?[]:["tests"]}}});return{itemId:l.item.id,tests:l.item.tests??[],testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:d}}function zb(e,t){let n=$o(e.pmContext);Pb(e.workspaceContext),Kb(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Gn(e.onlyIndex),onlyLast:e.onlyLast},i=e.timeout===void 0?void 0:ge(e.timeout,"--timeout");if(i!==void 0&&i<=0)throw new p(`--timeout must be a positive number (got "${e.timeout}")`,m.USAGE);Wb(e);let s=e.run===!0?Zv(t,r):void 0;if(s)for(let o of s.selected)Xn(o.command);return{defaultTimeoutSeconds:i,pmContextMode:n,runSelection:s,testsToRun:s?.selected??t}}async function o$(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await il(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===!0||(t.measure?.length??0)>0,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:qe(process.cwd())}})}function a$(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=nl(t);n.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}`)}return n}function c$(e){let t=QM(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),i=I(),s=Hr(e.options.measure,i);return{run_id:JM("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:i,recorded_at:i,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:s.length>0?s:void 0,executions:e.runResults.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}}async function d$(e){let{options:t,pmRoot:n,settings:r,itemId:i,runStartedAt:s,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let d=c$({options:t,runStartedAt:s,runResults:o,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Lo({pmRoot:n,settings:r,itemId:i,author:U(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(l){if(Ut(l))throw l;return c.push(`test_result_tracking_failed:${i}:${l instanceof Error?l.message:String(l)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function Lb(e,t,n){let r;if(e.metricBelow!==void 0){let i=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,i).trim(),o=e.metricBelow.slice(i+1).trim(),a=Number(o);if(i<=0||s.length===0||o.length===0||!Number.isFinite(a))throw new p("--metric-below must use name=value",m.USAGE);r=Fv(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Uv(t,e.metricDiff)}}async function l$(e,t,n){if(e.acknowledgeLinkedTests===!0)return Hg(t,n,I())}function u$(e){let{item:t,runResults:n,failureCategories:r,runSelection:i,failOnSkippedTriggered:s,warnings:o,recording:a,measurementProjection:c,restoreScope:d}=e,l=i!==void 0&&i.selector!==null&&i.skipped_count>0,u=ob(t.itemId,d);return{ok:n.every(_=>_.status!=="failed"&&_.status!=="refused")&&s!==!0,id:t.itemId,tests:l?i.selected:t.tests,...l?{tests_omitted:{count:t.tests.length-i.selected.length,restore_with:u}}:{},run_results:n,failure_categories:r,selection:i?{selector:i.selector,requested:i.requested,selected_indexes:i.selected_indexes,selected_count:i.selected_count,skipped_count:i.skipped_count}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:o.length>0?o: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 Bb(e,t,n){let r=eb(t);if(r)return tb(t),Wb(t),zd(e,t,n,R(process.cwd(),n.path)),{...await rb(e,{...r,author:t.author,message:t.message,force:t.force},n),run_results:[],failure_categories:Qr([])};let i=on(),s=R(process.cwd(),n.path);await F(s);let o=await x(s);zd(e,t,n,s),Hr(t.measure,"validation"),Lb(t,[],void 0);let a=P(o,M()),c=await i.resolveList(t.add,"--add"),d=await i.resolveList(t.addJson,"--add-json"),l=await i.resolveList(t.remove,"--remove"),u=[...cP(c),...uP(d)],_=await Dn(u,U(t.author,o.author_default),I())??[],h=mP(l),f=pP(t.removeIndex),g=await s$({id:e,options:t,pmRoot:s,settings:o,typeToFolder:a.type_to_folder,adds:_,removes:h,removeIndexes:f}),y=ra(()=>zb(t,g.tests)),w=await l$(t,s,g.tests),b=t.run===!0?I():void 0,k=await o$({options:t,runOptions:y,pmRoot:s,untrustedLinkedTestsPolicyEnabled:o.testing.allow_untrusted_linked_tests});ab(e,t,n,s,k);let C=Qr(k),S=t.run===!0&&t.failOnSkipped===!0&&k.some(N=>N.status==="skipped"),A=a$(t,k);w&&A.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let v=await d$({options:t,pmRoot:s,settings:o,itemId:g.itemId,runStartedAt:b,runResults:k,failOnSkippedTriggered:S,warnings:A}),T=v?.receipt.recorded?Xd([...g.testRuns,v.entry]):g.testRuns,L=Lb(t,T,v?.entry);return u$({item:g,runResults:k,failureCategories:C,runSelection:y.runSelection,failOnSkippedTriggered:S,warnings:A,recording:v,measurementProjection:L,restoreScope:sb(n,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]="22944f9f-02a6-5fb4-b13e-d034ec4cfa7d")}catch{}})();var m$=(e,t)=>{if(e===void 0)return;let n=se(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new p(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE)}return n},p$=e=>{if(e===void 0)return;let t=ge(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",m.USAGE);return t},Hb=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new p(`${t} must be a non-negative integer`,m.USAGE);return n},_$=e=>e instanceof Error?e.message:String(e),f$=()=>{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)}`},h$=e=>e.trim().replaceAll(/\s+/g," "),g$=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),y$=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),w$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},v$=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Fo=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Vb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),b$=e=>typeof e=="number"?e:void 0,k$=e=>{let t={assert_stdout_contains:Fo(e.assert_stdout_contains),assert_stdout_regex:Fo(e.assert_stdout_regex),assert_stderr_contains:Fo(e.assert_stderr_contains),assert_stderr_regex:Fo(e.assert_stderr_regex),assert_stdout_min_lines:b$(e.assert_stdout_min_lines),assert_json_field_equals:Vb(e.assert_json_field_equals),assert_json_field_gte:Vb(e.assert_json_field_gte)};return JSON.stringify(t)},E$=e=>{let t=sl(e.command);return t!==void 0?`command:${e.scope}:${h$(t)}`:`path:${e.scope}:${sl(e.path)??""}`},Yb=e=>{let t=g$(e.env_set),n=y$(e.env_clear),r=w$(e.pm_context_mode),i=v$(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",o=k$(e);return`${E$(e)}:${t}:${n}:${r}:${i}:${s}:${o}`},S$=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,T$=e=>{let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},C$=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Uo=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
27
|
+
`)}catch{}},A$=async(e,t,n)=>{let r=[],i=0;for(let s of e){let o=await Bb(s.id,{run:!1},{...t,path:n});i+=o.tests.length,r.push({item:s,tests:o.tests})}return{itemTests:r,linkedTests:i}},x$=async e=>{let t=q(e.settings.schema),n=P(e.settings,M()),r=m$(e.options.status,t),i=Hb(e.options.limit,"--limit"),s=Hb(e.options.offset,"--offset")??0,o=(await Ee(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(a=>r?a.status===r:!0).sort((a,c)=>a.id.localeCompare(c.id));return{filteredItems:i===void 0?o.slice(s):o.slice(s,s+i),statusFilter:r,limitFilter:i,offsetFilter:s}},R$=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let i=Yb(r);if(!t.has(i)){t.set(i,r.timeout_seconds);continue}t.set(i,S$(t.get(i),r.timeout_seconds))}return t};function I$(e,t){try{Xn(e.command);return}catch(n){if(!(n instanceof p)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var O$=async(e,t)=>{let n=[],r=e.tests.map(l=>{let u=Yb(l),_=I$(l,e.item.id);if(_)return{test:l,key:u,duplicate:!1,refusal:_};let h=t.seenTestKeys.has(u);if(!h){t.seenTestKeys.add(u);let f=t.effectiveTimeoutByKey.get(u);n.push(f===void 0?l:{...l,timeout_seconds:f})}return{test:l,key:u,duplicate:h,refusal:_}}),i=n.length>0?await il(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}):[],s=0,o=r.map(({test:l,key:u,duplicate:_,refusal:h})=>{if(h)return h;if(!_){let f=i[s];return s+=1,f}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),a=T$(o),c=Qr(o),d=await N$(e,a,o,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:d,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:o,failure_categories:c}}},L$=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),D$=e=>e?!0:void 0,N$=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let i=L$(t,r.options);await Lo({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:i?"failed":"passed",started_at:r.runStartedAt,finished_at:I(),recorded_at:I(),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:D$(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.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}))}})}catch(i){return Ut(i)?(r.revisionConflicts.push(i),[]):[`test_result_tracking_failed:${e.item.id}:${_$(i)}`]}return[]},M$=()=>{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},sl=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},P$=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:qe(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:R$(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:U(e.options.author,e.settings.author_default),trackingRunId:f$(),trackingAttempt:M$(),trackingResumedFrom:sl(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),$$=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Qr([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(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:i}},F$=async(e,t,n)=>{for(let[i,s]of e.entries()){Uo(t.options,`item ${i+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await O$(s,t);C$(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),Uo(t.options,`item ${i+1}/${e.length} end id=${s.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},U$=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),r=nl(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}`)},j$=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}),G$=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(" "),q$=async(e,t)=>{let n=R(process.cwd(),t.path);await F(n);let r=await x(n),i=await x$({pmRoot:n,settings:r,options:e}),s=p$(e.timeout),o=I(),a=await A$(i.filteredItems,t,n);return Uo(e,G$({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:o}},K$=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}},o8=async(e,t)=>{let n=await q$(e,t),{accumulation:r,failOnEmptyTestRunTriggered:i}=$$(e,n.linkedTests,n.filteredItems),s=P$({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await F$(n.itemTests,s,r),U$(e,r);let o=K$({options:e,accumulation:r,failOnEmptyTestRunTriggered:i});return Uo(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),j$({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})};import wF from"node:os";import Kn from"node:fs/promises";import{spawn as ek}from"node:child_process";import{createHash as W$,randomBytes as z$}from"node:crypto";import Zr 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]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}catch{}})();var tk=new Set(["queued","running"]),dl=new Set(["passed","failed","stopped","canceled"]),B$=3e3,H$=3e3,V$=3e4,nk=100,Xb=100;function rk(){return Date.now()}function ik(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function Y$(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function X$(){let e=Date.now().toString(36),t=z$(3).toString("hex");return`tr-${e}-${t}`}function J$(e,t,n){let r={kind:e,command:ik(t),pm_root:Zr.resolve(n)};return W$("sha256").update(JSON.stringify(r)).digest("hex")}function Wn(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function Q$(e){await bt(nu(e)),await bt(ea(e)),await bt(ru(e)),await bt(iu(e)),await bt(au(e))}async function sk(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new p(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,m.GENERIC_FAILURE)}}async function nt(e,t){let n={...t,updated_at:I()};await Le(ta(e,t.id),`${JSON.stringify(n,null,2)}
|
|
28
|
+
`)}async function zn(e,t){let n=ta(e,t),r=await Z(n);return r?sk(r,n):null}async function Z$(e){let t=ea(e);return await re(t)?(await Kn.readdir(t,{withFileTypes:!0})).filter(n=>n.isFile()&&n.name.endsWith(".json")).map(n=>Zr.join(t,n.name)).sort((n,r)=>r.localeCompare(n)):[]}function eF(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function tF(e){if(process.platform==="linux")try{let t=await Kn.readFile(`/proc/${e}/status`,"utf8");return eF(t)}catch{return}}function nF(e){let t=e.lastIndexOf(")");if(t<0)return{};let n=e.slice(t+2).trim().split(/\s+/),r=Number.parseInt(n[11],10),i=Number.parseInt(n[12],10);return!Number.isFinite(r)||!Number.isFinite(i)?{}:{cpu_user_seconds:r/Xb,cpu_system_seconds:i/Xb}}async function rF(e){if(process.platform!=="linux")return{};try{let t=await Kn.readFile(`/proc/${e}/stat`,"utf8");return nF(t)}catch{return{}}}async function al(e){let t=e.child_pid??e.worker_pid;if(!Wn(t))return;let n=await tF(t),r=await rF(t),i=e.started_at?Date.parse(e.started_at):Number.NaN,s=Number.isFinite(i)?Math.max(0,(rk()-i)/1e3):void 0;return{recorded_at:I(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:s}}function ol(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function iF(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:ol(a.passed),failed:ol(a.failed),skipped:ol(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let r=Array.isArray(n.run_results)?n.run_results:[],i=0,s=0,o=0;for(let a of r){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){i+=1;continue}if(c==="failed"||c==="refused"){s+=1;continue}o+=1}return{summary:{passed:i,failed:s,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function sF(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:I(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let r=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;let i=Number.parseInt(r[1],10),s=Number.parseInt(r[2],10),o=r[4]?Number.parseInt(r[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:i,linked_test_total:s,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:I(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function oF(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function cl(e,t){if(t<=0)return[];let n=oF(e);return n.length<=t?n:n.slice(n.length-t)}async function ok(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let i=Zr.resolve(e,t);if(await re(i))return i}let n=Zr.resolve(e,"dist","cli.js");if(await re(n))return n;let r=process.argv[1]?.trim();if(r&&r.length>0){let i=Zr.resolve(e,r);if(await re(i))return i}throw new p("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",m.GENERIC_FAILURE)}async function ei(e,t){if(!tk.has(t.status)||Wn(t.worker_pid)||t.finished_at)return t;let n={...t,status:"failed",finished_at:I(),error:t.error??"Background test run worker exited before writing terminal status."};return await nt(e,n),n}async function ll(e){await Q$(e.pmRoot);let t=ik(e.commandArgs);if(t.length===0)throw new p("Background test run requires command arguments.",m.USAGE);let n=J$(e.kind,t,e.pmRoot),r=await ml(e.pmRoot,{});for(let l of r){let u=await ei(e.pmRoot,l);if(u.fingerprint===n&&!(!tk.has(u.status)||!Wn(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let i=X$(),s=I(),o=su(e.pmRoot,i),a=ou(e.pmRoot,i),c=cu(e.pmRoot,i);await Kn.writeFile(o,"","utf8"),await Kn.writeFile(a,"","utf8");let d={id:i,kind:e.kind,status:"queued",created_at:s,updated_at:s,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:Y$(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:s}};return await nt(e.pmRoot,d),{started:!0,run:d}}async function ul(e){let t=await zn(e.pmRoot,e.runId);if(!t)throw new p(`Background test run ${e.runId} not found`,m.NOT_FOUND);if(dl.has(t.status))throw new p(`Background test run ${t.id} is already terminal (${t.status}).`,m.CONFLICT);let n=await ok(process.cwd()),r=[];e.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",t.pm_root,"test-runs-worker",t.id);let i={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},s=ek(process.execPath,[n,...r],{cwd:process.cwd(),env:i,detached:!0,stdio:"ignore",windowsHide:!0});s.unref();let o={...t,status:"queued",worker_pid:s.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:I()}};return await nt(e.pmRoot,o),o}async function Jb(e,t,n){await e,await Kn.appendFile(t,n,"utf8")}function ak(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function aF(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function cF(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function dF(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await nt(e,t)}catch{}})},async flush(){await n}}}function Qb(e,t){try{e.kill(t)}catch{}}async function lF(e,t,n,r){n.stopRequested||(n.stopRequested=!0,e.stop_requested_at=I(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:I()},r(),Qb(t,"SIGTERM"),setTimeout(()=>Qb(t,"SIGKILL"),ak("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",H$)).unref?.())}function uF(e,t,n){return{phase:n,message:e,heartbeat_at:I(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function mF(e,t,n,r){return{phase:r,message:e,heartbeat_at:I(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function Zb(e,t,n){let r=sF(t);if(!r)return!1;let i=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=r.item_id?uF(t,r,i):mF(t,e,r,i),r.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function pF(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function _F(e,t,n){return n?"stopped":e===0&&t.failed===0&&t.fail_on_skipped_triggered!==!0?"passed":"failed"}function fF(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:I(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function hF(e,t,n){if(t!==null){await Le(e.result_path,`${JSON.stringify(t,null,2)}
|
|
29
|
+
`);return}await Le(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:cl(n,nk)},null,2)}
|
|
30
|
+
`)}async function ck(e,t,n=!1){let r=await zn(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let i={...r,status:"running",started_at:r.started_at??I(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:I()}},s=await ok(process.cwd()),o=aF(i);await nt(e,i);let a=cF(i,n),c=ek(process.execPath,[s,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});i.child_pid=c.pid;let d=dF(e,i),l=d.schedule,u=Promise.resolve(),_=Promise.resolve(),h="",f="",g={stopRequested:!1},y=()=>{lF(i,c,g,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let w=setInterval(()=>{(async()=>(i.resource=await al(i),i.progress.heartbeat_at=I(),l()))()},ak("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",B$));w.unref?.(),c.stdout?.on("data",v=>{let T=v.toString("utf8");h+=T,u=Jb(u,i.stdout_path,T)}),c.stderr?.on("data",v=>{let T=v.toString("utf8");_=Jb(_,i.stderr_path,T),f+=T;let L=f.split(/\r?\n/);f=L.pop();let N=!1;for(let E of L){let $=E.trimEnd();$.length>0&&Zb(i,$,g.stopRequested)&&(N=!0)}N&&l()});let b=null,k=null;try{({code:b,signal:k}=await new Promise(v=>{c.on("close",(T,L)=>{v({code:T,signal:L})})}))}finally{clearInterval(w),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await _;let C=f.trimEnd();C.length>0&&Zb(i,C,g.stopRequested)&&l(),f="";let S=pF(h),A=iF(i.kind,S);return i.summary=A.summary,i.exit_code=typeof b=="number"?b:void 0,i.signal=k??void 0,i.finished_at=I(),i.status=_F(i.exit_code,A.summary,g.stopRequested),i.progress=fF(i,g.stopRequested),i.resource=await al(i),await hF(i,S,h),await nt(e,i),await d.flush(),i}async function ml(e,t){let n=await Z$(e),r=[];for(let a of n){let c=await Z(a);if(!c)continue;let d=await sk(c,a);r.push(d)}let i=[];for(let a of r)i.push(await ei(e,a));let s=(t.status?i.filter(a=>a.status===t.status):i).sort((a,c)=>{let d=Date.parse(c.updated_at)-Date.parse(a.updated_at);return Number.isFinite(d)&&d!==0?d:c.id.localeCompare(a.id)}),o=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return o===void 0?s:s.slice(0,o)}async function dk(e,t){let n=await zn(e,t);if(!n)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let r=await ei(e,n),i=Wn(r.worker_pid),s=Wn(r.child_pid);r.status==="running"&&!s&&!r.finished_at&&!i&&(r.status="failed",r.finished_at=I(),r.error=r.error??"Background run process exited unexpectedly.",await nt(e,r)),r.status==="running"&&(r.resource=await al(r),await nt(e,r));let o=r.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,rk()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:V$,u=r.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:r,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:i,child_alive:s}}}function gF(e,t){let n=t?"SIGKILL":"SIGTERM";if(!Wn(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function yF(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:I(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function lk(e,t,n=!1){let r=await zn(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let i=await ei(e,r);if(dl.has(i.status))return{run:i,signal_sent:"none"};let s=gF(i,n);return s==="none"&&(i.status="stopped",i.finished_at=i.finished_at??I()),i.stop_requested_at=I(),i.progress=yF(i,s),await nt(e,i),{run:i,signal_sent:s}}async function uk(e,t,n,r=!1){let i=await zn(e,t);if(!i)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let s=await ei(e,i);if(!dl.has(s.status))throw new p(`Background test run ${t} is not terminal and cannot be resumed.`,m.CONFLICT);let o=await ll({pmRoot:s.pm_root,globalPmRoot:s.global_pm_root,kind:s.kind,commandArgs:s.command_args,requestedBy:n,targetId:s.target_id,statusFilter:s.status_filter,resumedFrom:s.id,resumedBy:n,attempt:s.attempt+1});if(!o.started)return o.run;let a=await ul({pmRoot:e,runId:o.run.id,noExtensions:r}),c={...s,resumed_by:a.id};return await nt(e,c),a}async function mk(e,t,n,r){let i=await zn(e,t);if(!i)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let s=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):nk,o=n==="stdout"||n==="both"?await Z(i.stdout_path)??"":"",a=n==="stderr"||n==="both"?await Z(i.stderr_path)??"":"";return{run:i,stream:n,tail:s,stdout:n==="stdout"||n==="both"?cl(o,s):[],stderr:n==="stderr"||n==="both"?cl(a,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]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();var vF=["queued","running","passed","failed","stopped","canceled"],bF=["stdout","stderr","both"];function kF(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(vF.includes(t))return t;throw new p(`Invalid --status value "${e}"`,m.USAGE)}function EF(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(bF.includes(t))return t;throw new p(`Invalid --stream value "${e}"`,m.USAGE)}function SF(){try{let e=wF.userInfo().username.trim();if(e.length>0)return e}catch{}}function pk(e,t){let n=[e,Wu(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,SF()];for(let r of n){if(typeof r!="string")continue;let i=r.trim();if(i.length>0)return i}return"unknown"}async function nn(e){await F(e)}async function A8(e,t){let n=R(process.cwd(),t.path),r=qe(process.cwd());await nn(n);let i=await x(n),s=pk(e.author,i.author_default),o=await ll({pmRoot:n,globalPmRoot:r,kind:e.kind,commandArgs:e.commandArgs,requestedBy:s,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await ul({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function x8(e,t){let n=R(process.cwd(),t.path);await nn(n);let r=kF(e.status),i=ir(e.limit,"limit"),s=await ml(n,{status:r,limit:i});return{runs:s,count:s.length,filters:{status:r,limit:i}}}async function R8(e,t){let n=R(process.cwd(),t.path);await nn(n);let r=await dk(n,e);return{run:r.run,health:r.health}}async function I8(e,t,n){let r=R(process.cwd(),n.path);await nn(r);let i=EF(t.stream),s=ir(t.tail,"tail"),o=await mk(r,e,i,s);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function O8(e,t,n){let r=R(process.cwd(),n.path);await nn(r);let i=await lk(r,e,t.force===!0);return{run:i.run,signal_sent:i.signal_sent}}async function L8(e,t,n){let r=R(process.cwd(),n.path);await nn(r);let i=await x(r),s=pk(t.author,i.author_default),o=await uk(r,e,s,t.noExtensions===!0);return{resumed_from:e,run:o}}async function D8(e,t){let n=R(process.cwd(),t.path);await nn(n);let r=await ck(n,e,t.noExtensions===!0);return{id:r.id,status:r.status,exit_code:r.exit_code}}export{c0 as a,of as b,CF as c,p0 as d,En as e,_0 as f,IF as g,OF as h,$a as i,LF as j,DF as k,NF as l,g0 as m,MF as n,PF as o,$F as p,FF as q,Fa as r,pf as s,jF as t,mf as u,gf as v,A0 as w,_r as x,L0 as y,wf as z,M0 as A,ZF as B,Ua as C,kf as D,$0 as E,r1 as F,i1 as G,Ef as H,s1 as I,o1 as J,D as K,Ce as L,et as M,Sn as N,ja as O,Tf as P,ut as Q,fr as R,z0 as S,Ka as T,Wa as U,Rf as V,Cn as W,gr as X,Ba as Y,lE as Z,Mf as _,yr as $,$f as aa,Zi as ba,Ha as ca,Ff as da,Uf as ea,jf as fa,W1 as ga,oU as ha,RS as ia,qt as ja,aU as ka,IS as la,mh as ma,cU as na,br as oa,dU as pa,ph as qa,PS as ra,gh as sa,wU as ta,Sr as ua,vU as va,KS as wa,WS as xa,bU as ya,zS as za,kh as Aa,nT as Ba,rT as Ca,iT as Da,sT as Ea,Cr as Fa,oT as Ga,_t as Ha,aT as Ia,cT as Ja,dT as Ka,Za as La,ec as Ma,lT as Na,is as Oa,ss as Pa,Eh as Qa,Ch as Ra,cj as Sa,bT as Ta,kT as Ua,Ih as Va,rc as Wa,mj as Xa,gj as Ya,Nh as Za,Ph as _a,Mj as $a,Pj as ab,Ar as bb,ls as cb,jh as db,Gh as eb,qh as fb,Kh as gb,Hh as hb,VT as ib,XT as jb,JT as kb,QT as lb,Qh as mb,Zh as nb,eg as ob,ms as pb,ps as qb,Ag as rb,gq as sb,xg as tb,Ig as ub,Og as vb,Ng as wb,Pg as xb,Ic as yb,Lr as zb,Dr as Ab,HA as Bb,Dn as Cb,Wg as Db,Fc as Eb,Bg as Fb,Hg as Gb,bx as Hb,w2 as Ib,Ky as Jb,Pr as Kb,By as Lb,Hy as Mb,Vy as Nb,td as Ob,RR as Pb,nW as Qb,ew as Rb,TW as Sb,RW as Tb,WR as Ub,Ns as Vb,sd as Wb,nw as Xb,GW as Yb,sI as Zb,Ms as _b,Ps as $b,Fs as ac,mw as bc,Vt as cc,Gs as dc,Ht as ec,lw as fc,Fr as gc,Ur as hc,qs as ic,Ks as jc,Yt as kc,Xt as lc,Pn as mc,Ws as nc,zs as oc,Bs as pc,jr as qc,co as rc,SI as sc,ad as tc,yB as uc,Zt as vc,XO as wc,Fw as xc,Uw as yc,jw as zc,gH as Ac,uL as Bc,RL as Cc,OL as Dc,Wr as Ec,yH as Fc,Ad as Gc,kH as Hc,vD as Ic,xd as Jc,GH as Kc,qH as Lc,vo as Mc,rV as Nc,iV as Oc,sV as Pc,fv as Qc,bV as Rc,MD as Sc,Md as Tc,PD as Uc,$D as Vc,FD as Wc,kV as Xc,EV as Yc,PV as Zc,$V as _c,FV as $c,Ov as ad,Lv as bd,QD as cd,Dv as dd,o4 as ed,Nv as fd,a4 as gd,c4 as hd,ko as id,fN as jd,f4 as kd,$d as ld,h4 as md,Fd as nd,hN as od,Hr as pd,Fv as qd,Uv as rd,U4 as sd,qv as td,Z4 as ud,e5 as vd,rb as wd,zd as xd,nl as yd,G3 as zd,SP as Ad,Qr as Bd,xP as Cd,il as Dd,Bb as Ed,o8 as Fd,A8 as Gd,x8 as Hd,R8 as Id,I8 as Jd,O8 as Kd,L8 as Ld,D8 as Md};
|
|
31
|
+
//# sourceMappingURL=chunk-5Z6LWFDL.js.map
|