@unbrained/pm-cli 2026.10.28 → 2026.10.31
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 +50 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/commands/lifecycle/append.d.ts +4 -0
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/create.d.ts +4 -0
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/plan.d.ts +3 -0
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/error-guidance.d.ts +45 -5
- package/dist/cli/error-guidance.js +5 -3
- package/dist/cli/extension-command-help.d.ts +1 -0
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli/help-content.js +2 -2
- package/dist/cli/main.d.ts +1 -5
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.d.ts +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/preflight-warnings.d.ts +11 -0
- package/dist/cli/preflight-warnings.js +4 -0
- package/dist/cli/register-list-query.js +3 -3
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-24J6TNYE.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-YYD5MNAV.js → chunk-2AHSPMKJ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35Q2B2GJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-43R7UTWV.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6PSDQ7T7.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-YUBUNECD.js → chunk-BS2KXT24.js} +84 -84
- package/dist/cli-bundle/chunks/{chunk-D3AIQZXF.js → chunk-GMBDZID5.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-HSBTITO4.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-LWW4F4G2.js → chunk-MRUA2Z43.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-P3LNMWL2.js +2 -0
- package/dist/cli-bundle/chunks/chunk-PT7TS6E7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D6P6IBPN.js → chunk-TL3O5GZA.js} +45 -45
- package/dist/cli-bundle/chunks/chunk-U7JXZMU5.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-DM3PICGU.js → chunk-V6EWBTNH.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VC7TA67O.js +20 -0
- package/dist/cli-bundle/chunks/chunk-WNF6FOL7.js +31 -0
- package/dist/cli-bundle/chunks/chunk-WRXQAW7Q.js +114 -0
- package/dist/cli-bundle/chunks/{chunk-RZQNFHXO.js → chunk-WX25MU4N.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-XDDPSWIW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YT5D5HNG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZTJVOBDU.js +128 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-LHLE7PSG.js → indexed-receipt-blobs-KGMJVFH2.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-UWV6UNSV.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-GKDKHRTZ.js → mutation-admission-I4RHIT3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-MHJJUM6M.js → register-list-query-MVDL5EXG.js} +6 -6
- package/dist/cli-bundle/chunks/register-mutation-GAF7LXRB.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-JLFRL36Q.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-WUZ2ZSMY.js → register-setup-MZN6ONB3.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-MN3Y7LVX.js → settlement-hook-YWSWFOZY.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-2FYJGGG3.js → stage-2ZORTOF6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4GN2ZPT5.js → chunk-2J7T2UCH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YLVHHWHN.js → chunk-4PW5XWVI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4QPGJO2G.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IQKLJFJE.js → chunk-57HPXGOQ.js} +18 -18
- package/dist/cli-bundle/focused-chunks/chunk-5MCGYBOQ.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-6F6APBCX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AFVN2KCP.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ON5WFDCG.js → chunk-DFUTCKUF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EA65HVBO.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-GP2WU43K.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-C2GLO7HU.js → chunk-HPWT3RBG.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-HSAEEWSI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7SZPZOIC.js → chunk-JLXGRDTG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-JNKRUCVZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JTCGDODH.js → chunk-KH5QJXY7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KKRIFBSL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TUN4M757.js → chunk-MW77Q3AQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +22 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DRN4W3YJ.js → chunk-NRBUMDLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ML5JIUM6.js → chunk-PC3R5CJV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PFBQOZPK.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-R3EA3SDW.js → chunk-QFMJGQGO.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-I4X6AKOO.js → chunk-SFQKCA5K.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WHIE2C6Q.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y6UYRMVG.js +6 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-5H6RMRTK.js → indexed-receipt-blobs-KHWT44EK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-LU75EG7D.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-admission-TM3SVU2O.js → mutation-admission-KDJ7SCPA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-LBVWWSCF.js → settlement-hook-SJV52ZTV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-7ZBRX2Q2.js → stage-R4KEBO37.js} +2 -2
- package/dist/cli-bundle/main.js +26 -22
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -43
- 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 +61 -61
- 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/nested-settings.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +4 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/history/operation-contract.d.ts +2 -2
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/item/literal-mutation-input.d.ts +12 -0
- package/dist/core/item/literal-mutation-input.js +2 -0
- package/dist/core/item/parse.d.ts +2 -0
- package/dist/core/item/parse.js +2 -2
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/output.js +3 -3
- package/dist/core/schema/fields-file.js +1 -1
- package/dist/core/sentry/helpers.d.ts +6 -0
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.d.ts +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.d.ts +6 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/output-unicode.d.ts +10 -0
- package/dist/core/shared/output-unicode.js +2 -0
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/core/telemetry/policy.d.ts +8 -0
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/runtime.js +3 -3
- package/dist/sdk/agent/command-recovery.d.ts +15 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +28 -0
- package/dist/sdk/cli-contracts/agent-output-contracts.js +2 -2
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-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-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion/fish.js +4 -4
- package/dist/sdk/completion/zsh.js +3 -3
- package/dist/sdk/config.d.ts +1 -0
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/core.d.ts +1 -0
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/error-runtime.d.ts +9 -0
- package/dist/sdk/error-runtime.js +1 -1
- 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/index.d.ts +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -2
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/append.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.d.ts +4 -0
- package/dist/sdk/lifecycle/cli-input.js +2 -0
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/plan.d.ts +2 -3
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +45 -0
- package/dist/sdk/lifecycle/repeated-terminal-state.js +2 -0
- package/dist/sdk/lifecycle/shared-unset-fields.d.ts +9 -0
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/update-many.d.ts +0 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +29 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/output/table-rows.d.ts +15 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.d.ts +18 -0
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/get.d.ts +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.d.ts +2 -0
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/next-ranking-policy.d.ts +35 -0
- package/dist/sdk/query/next-ranking-policy.js +2 -0
- package/dist/sdk/query/next.d.ts +12 -2
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/projection-contracts.d.ts +4 -0
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/surfaces.d.ts +27 -0
- package/dist/sdk/read-output/surfaces.js +2 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.d.ts +16 -0
- package/dist/sdk/runtime/mutation-value-validation.js +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +14 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/test/execution-receipts.d.ts +25 -0
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.d.ts +5 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +54 -0
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +12 -0
- package/docs/AGENT_UX_CONTRACTS.md +2 -1
- package/docs/COMMANDS.md +73 -15
- package/docs/CONFIGURATION.md +48 -1
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +24 -2
- package/docs/PACKED_FIRST_RUN.md +2 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
- package/docs/SDK.md +207 -11
- package/docs/TESTING.md +46 -2
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
- 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-2J7I54MQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7V37RC2L.js +0 -114
- package/dist/cli-bundle/chunks/chunk-AHVN4GHF.js +0 -31
- package/dist/cli-bundle/chunks/chunk-CS7QDSUX.js +0 -128
- package/dist/cli-bundle/chunks/chunk-CXUQEZDX.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DKLEDWVW.js +0 -3
- package/dist/cli-bundle/chunks/chunk-E5QBZ4HI.js +0 -8
- package/dist/cli-bundle/chunks/chunk-JESLOJD7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-PQLRKFPZ.js +0 -20
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHONSCLJ.js +0 -6
- package/dist/cli-bundle/chunks/chunk-ZX3XMTZG.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-SN425O3R.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-EYUIUGPW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-46WLWK73.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6L4KKRK7.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-6VDRAJYX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-B4ZQJEMT.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-BZSACRVX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-F6UQJJYB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-L5GX2FGZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LPWZERVD.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-OASYSUOH.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-QUPGBO2L.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-Z26ZPQH6.js +0 -3
|
@@ -1,65 +1,65 @@
|
|
|
1
|
-
import{c as Et,d as sn,e as cn,f as dn,g as Tl,j as Dl}from"./chunk-R3EA3SDW.js";import{a as Cl}from"./chunk-ON5WFDCG.js";import{d as Q,h as Ya,s as El}from"./chunk-L5GX2FGZ.js";import{a as Na,c as Ui,d as Hi,e as Vc,g as Kc,h as ja,i as Yc,j as Kt,k as Yt,l as Xc,m as Zc,n as Fa,o as td,p as Xt,q as Zt,r as nd,s as id,t as Ua}from"./chunk-B4ZQJEMT.js";import{a as za}from"./chunk-SVOOGGAK.js";import{B as hd,C as Bi,D as _d,E as Ha,G as gd,H as yd,J as wd,K as vd,L as Ji,U as Vi}from"./chunk-Z26ZPQH6.js";import{K as $l}from"./chunk-I4X6AKOO.js";import{A as Al,I as Za,w as Il,y as Xa,z as Rl}from"./chunk-F6UQJJYB.js";import{$ as ur,Aa as Ka,C as Sd,G as xd,H as Id,I as Rd,L as sr,Na as wl,Oa as vl,Sa as bl,Ta as kl,aa as Kd,ba as Ba,ca as qn,ea as Ja,i as Ki,ia as sl,ja as cl,ka as dl,la as ll,m as Fn,ma as fr,n as bd,o as kd,oa as ul,p as Un,pa as ml,qa as pl,ra as Mt,sa as fl,ta as an,ua as hl,va as Va,wa as on,x as Ed,xa as _l,ya as gl,za as yl}from"./chunk-OASYSUOH.js";import{a as qc,b as Vt,c as Ma,d as Gc,e as Bc,f as tt,g as zi,h as Jc,i as yt}from"./chunk-4GN2ZPT5.js";import{m as Gn,o as hr,v as Sl,y as xl}from"./chunk-6VDRAJYX.js";import{B as mr,D as rl,E as ge,F as ye,G as al,H as pr,I as it,J as rt,N as ol,O as at,a as Yi,c as qd,j as Yd,k as Xd,m as Zd,n as Qd,o as kt,p as el,q as tl,v as nl,w as il}from"./chunk-BZSACRVX.js";import{$a as lr,Aa as zd,Ca as rr,Da as ar,Ea as zn,Fa as bt,Ga as Wn,Ha as Wd,Ia as or,Ja as Nt,Ka as ae,La as cr,Ma as Gd,Na as Ga,Oa as dr,Pa as nn,Qa as rn,Sa as Bd,Ta as Jd,Wa as Me,Za as Vd,_a as T,a as Ad,aa as z,ba as Ld,ca as nt,d as Re,da as Nd,db as te,e as Wa,f as Cd,ja as Md,k as Xi,ka as qa,l as Hn,la as tr,m as Td,ma as en,n as Zi,o as $d,oa as nr,pa as jd,q as Qi,qa as Fd,r as er,sa as Ud,t as Dd,u as $e,ua as Hd,x as vt,xa as ir,y as Od,z as Pd,za as tn}from"./chunk-IQKLJFJE.js";import{b as Gt}from"./chunk-ML5JIUM6.js";import{a as se,c as Te,e as Ie,f as Ve,j as fe,k as Qc,l as Wi,n as ed}from"./chunk-TUN4M757.js";import{Ad as Qt,Ba as $c,Bb as Uc,Bd as wt,Ca as Ot,Cb as Hc,Cc as ld,Cd as Lt,Dc as le,Ea as Dc,Fa as A,Ga as Oc,Ha as xe,Hd as md,Ja as Fi,Ka as Pc,Kb as zc,Kd as pd,La as Da,Lb as Pt,Ld as fd,Ma as Oa,Md as re,Na as Pa,Nb as La,O as xc,Ob as Wc,Pa as Lc,Pb as Jt,Qa as Nc,R as Ic,Rb as Be,T as $a,Ta as Mc,Tb as Je,Wb as rd,Y as me,Yb as qi,Z as qe,Zb as ad,_ as Rc,_b as od,a as gc,aa as Y,ac as sd,bb as jc,d as yc,da as Ac,e as wc,ic as F,kb as Fc,mc as K,o as Ta,oa as Cc,oc as Ne,pa as Tc,pc as cd,qa as H,qc as Gi,va as jn,wa as M,xa as Ge,xc as dd,ya as ji,yd as $,za as Bt,zd as ud}from"./chunk-6L4KKRK7.js";import{a as _r,b as Bn}from"./chunk-EGN2HFRU.js";import{A as Mn,B as D,C as gt,D as j,E as B,H as Z,a as Li,d as Ni,o as vc,q as bc,s as kc,u as Ec,v as Mi,w as Sc,y,z as g}from"./chunk-7SZPZOIC.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]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},we=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ke=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 ln(e){try{return await e()}catch(t){throw t instanceof L?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Qa(e){try{return await e()}catch(t){throw t instanceof we?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as cg}from"node:crypto";import dg 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 un=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 Pl=1,jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],eo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],lg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],ug=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,gr=30,yr=5e3,Ll=4,mg=50;function ot(e,t){if(!ug.test(e))throw new L(`${t} must be a stable lowercase id`)}function pg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Jn(e){let t=lg.filter(r=>e[r]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function no(e,t){return A(e)===A(t)}function Nl(e,t){if(t.polarity==="equals")return no(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let i=t.value;return e.every(r=>i.includes(r))}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 Ml(e){let t=Jn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Nl(i.observed,t)===(i.expected==="pass"))}function fg(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,i=t.value;return!Array.isArray(n)||!Array.isArray(i)||i.some(r=>!n.includes(r))}return!no(e.value,t.value)}function hg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||A(e.scope)!==A(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return fg(Jn(e),Jn(t))||n[t.enforcement]<n[e.enforcement]||i}function _g(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,i=Number(t)+Number(n);if(e.field!==void 0&&i!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new L("items source equals/state requires field")}function gg(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("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 L("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 L("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 L("dependency_kind source source_kind_state must be present or missing")}function yg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("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 L("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 L("prose_edge_gap exemption selectors must not be empty")}}function io(e){ot(e.id,"measurement.id"),e.max_cost!==void 0&&pg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${eo.join(", ")}`);let n=Reflect.get(t,"kind");if(!eo.includes(n))throw new L(`measurement.source.kind must be one of ${eo.join(", ")}`);let i=t;if(i.kind==="items"&&_g(i),i.kind==="dependency_kind"&&gg(i),i.kind==="prose_edge_gap"&&yg(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new L(`${i.kind} source requires field`);return i.kind==="provider"&&(ot(i.provider,"provider source provider"),ot(i.key,"provider source key")),e}function ro(e){if(ot(e.id,"assertion.id"),ot(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=Jn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`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 L("retired assertion requires retire_reason");e.scope.kind==="filter"&&ot(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new L("assertion negative control requires pass and fail cases");if(!Ml(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function wg(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)ot(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!jt.includes(t))throw new L(`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 L(`gate provider policy trigger ${t} is invalid`)}}function jl(e){if(ot(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)ot(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${jt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!jt.includes(t))throw new L(`gate trigger must be one of ${jt.join(", ")}`);return e.provider_policy&&wg(e.provider_policy),e}function mn(e){if(e.version!==Pl)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(io(i),t.has(`measurement:${i.id}`))throw new L(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(ro(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){jl(i);let r=i.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(r.length>0)throw new L(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new L(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of Fl(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function ao(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ao(n,t)}function Fl(e){let t=new Map,n=(i,r)=>{let a=t.get(i)??[];a.push(r),t.set(i,a)};for(let i of e.assertions)n(i.measurement_id,`assertion ${i.id}`),i.scope.kind==="filter"&&n(i.scope.measurement_id,`assertion ${i.id} scope`);for(let i of e.measurements){if(i.source.kind!=="derived")continue;let r=[];ao(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function vg(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let a=n.pop();if(i.has(a))continue;i.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&ao(o.source.expression,n)}return r}function Vn(){return{version:Pl,measurements:[],assertions:[],gates:[]}}function bg(e,t){let n=t.items.filter(i=>(e.statuses===void 0||e.statuses.includes(i.status))&&(e.types===void 0||e.types.includes(i.type))&&(e.tags===void 0||e.tags.every(r=>i.tags?.includes(r)))&&(e.field===void 0||(()=>{let r=i[e.field];if(e.state!==void 0){let a=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?a:!a}return no(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function kg(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 Eg(e,t){let n=[],i=$a(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=$a(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&kg(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Sg(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 i=e[n];if(Array.isArray(i)){for(let r of i)if(typeof r=="string")t.push(r);else if(typeof r=="object"&&r!==null){let a=Reflect.get(r,"text");typeof a=="string"&&t.push(a)}}}return t}function xg(e,t,n,i){return e.some(r=>r.holder_id.trim().toLowerCase()===t.toLowerCase()&&(r.target_id===void 0||r.target_id.trim().toLowerCase()===n.toLowerCase())&&(r.text_contains===void 0||i.toLowerCase().includes(r.text_contains.trim().toLowerCase())))}function to(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Ig(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(to(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(to(o.id,s));for(let s of Sg(o)){let c=[...s.matchAll(r)].map(d=>d[0]);a+=c.length,i.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:a}}function Rg(e,t){let n=Ig(t.items),i=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=to(o.holder_id,d);if(n.linked_pairs.has(l)||xg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],a=r.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function Ag(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 Cg(e,t){let n=t.items.filter(i=>{let r=i[e.link],a=Array.isArray(r)&&r.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Tg(e,t){let n=e.source;return n.kind==="items"?bg(n,t):n.kind==="dependency_kind"?Eg(n,t):n.kind==="prose_edge_gap"?Rg(n,t):n.kind==="history"?Ag(n,t):n.kind==="links"?Cg(n,t):null}function Ul(e,t){return e.reduce((n,i)=>({units:n.units+i.units,items_scanned:n.items_scanned+i.items_scanned,history_entries:n.history_entries+i.history_entries,provider_calls:n.provider_calls+i.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function $g(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,i)=>n+i,0);if(e==="subtract")return t.slice(1).reduce((n,i)=>n-i,t[0]);if(e==="multiply")return t.reduce((n,i)=>n*i,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,i)=>n/i,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Hl(e,t,n){let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o],o)}});return await Promise.all(a),i}async function zl(e,t,n,i,r){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 s=await Wl(o,t,n,i,r);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[s.cost];return r.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await Hl(e.operands,Ll,o=>zl(o,t,n,i,r));return{value:$g(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Dg(e,t,n,i,r){io(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await zl(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Tg(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()-a},l=Ul([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new we(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${cg("sha256").update(A(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Wl(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let a=r.cache.get(e.id);if(a)return a;let o=Dg(e,t,n,i,r).catch(s=>{if(s instanceof Ke&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Ke(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function oo(e,t,n=[e]){return Wl(e,t,n,[],{cache:new Map,charged:new Set})}function Og(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 Pg(e,t,n={}){ro(e);let i=Jn(e),r=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:i,distance:Og(t.value,i),verdict:r?"retired":Nl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Ml(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Lg(e,t,n,i){let r=vg(e,t);if(r.size===0)return;let a=e.provider_policy,o=a?.triggers[i];if(!a||!o)throw new we(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!s.has(d))throw new we(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new we(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new we(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new we(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Ol(e,t,n,i,r){try{return await oo(n,i,r)}catch(a){if(a instanceof Ke){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new we(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function ql(e,t,n,i){mn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new we(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new we(`assurance gate ${e} does not declare trigger ${i.trigger}`);Lg(r,t,n,i.trigger);let a=await Hl(r.assertion_ids,Ll,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await Ol(r.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Pg(d,await Ol(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:r.id,tree_id:n.tree_id,trigger:i.trigger,dry_run:i.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Ul(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function wr(e){return dg.join(e,"assurance.json")}async function Gl(e){let t=await B(wr(e));return t===null?Vn():vr(t)}function vr(e){try{return mn(JSON.parse(e))}catch(t){throw new g("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.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 br(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Ng(e,t){e==="measurement"?io(t):e==="assertion"?ro(t):jl(t)}async function Kn(e,t){let n=structuredClone(br(await Gl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Bl(e,t,n){let i=br(await Gl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function kr(e,t,n,i={}){Ng(t,n);let r=await T(e),a=z(i.author,r.author_default),o=await nn({pmRoot:e,filePath:wr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Vn():vr(s),d=br(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&hg(d[l],n)){let m=n.authorization_decision;if(!m||!i.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),mn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
|
-
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function
|
|
3
|
-
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function
|
|
4
|
-
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function
|
|
5
|
-
`)>Zd)throw new g("Policy registry exceeds its byte ceiling.",y.USAGE);return o}async function eu(e,t,n,i){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:Ql(e,t,await kt(i.pmRoot),n)};let r=await nn({pmRoot:i.pmRoot,filePath:Fg.join(i.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:i.author,message:n.message,lockTtlSeconds:i.settings.locks.ttl_seconds,lockWaitMs:i.settings.locks.wait_ms,mutate(a){let o=Ql(e,t,Qd(a),n);return{raw:`${JSON.stringify(o,null,2)}
|
|
6
|
-
`,result:o}}});return{policy_result:!0,action:e,changed:r.changed,result:r.result}}async function zg(e,t,n){let i,r=await ol({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:i}),async mutate(a){let o=(await kt(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new g("--policy must name an approval rule.",y.USAGE);if(!o.rule.authors.includes(n.author))throw new g("This actor is not a declared approver.",y.CONFLICT);return await el(n.pmRoot,a.metadata.id),i={policy_id:o.id,policy_fingerprint:Lc(o),content_fingerprint:Nc(o,{...a.metadata,body:a.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:r.item.id,...i,warnings:r.warnings}}}function Wg(e,t){let n=tu(t),i=Oa({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==i.id)throw new g("Policy id operand does not match definition.id.",y.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return i}async function tT(e,t,n={},i={}){if(!Fi.includes(e))throw new g("Unknown workflow policy action.",y.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:Ug()};let r=await Hg(i,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await kt(r.pmRoot)};if(e==="policy-put"){let l=Wg(t,n.definition);return eu(e,l.id,{...n,definition:l},r)}if(!t?.trim())throw new g(`schema ${e} requires an operand.`,y.USAGE);if(["policy-remove","policy-mode"].includes(e))return eu(e,t,n,r);if(e==="policy-approve"){if(n.dryRun)throw new g("Use policy-check to preview; policy-approve records an approval.",y.USAGE);return zg(t,n,r)}let a=H(r.settings,F()),o=await ge(r.pmRoot,t,r.settings.id_prefix,r.settings.item_format,a.type_to_folder);if(!o)throw new g(`Item ${t} not found.`,y.NOT_FOUND);let{document:s}=await ye(o,{schema:r.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...tu(n.definition)};if(d.id!==c.id)throw new g("Policy preview cannot change the item id.",y.USAGE);return{policy_result:!0,action:e,changed:!1,result:await tl(r.pmRoot,await kt(r.pmRoot),{operation:"update",author:r.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as iu}from"node:crypto";import Xn from"node:fs/promises";import Zn 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 De(e,t){throw new g(e,y.USAGE,t)}var qg="2026-07-15T06:22:12.276Z",Gg=Date.parse(qg),Bg=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],nu=e=>typeof e=="string"?e:"",ru=e=>{let t=e??{},n=nu(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(nu(t.ts))>=Gg);return Bg[i][r]};function au(e,t,n=20,i=new Set,r=!1){let a=[],o=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}d+=1;let h=ru(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,r&&h==="actionable_unknown"&&o.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:s.legacy_unknown+s.actionable_unknown>a.length,actionable_events:o}}var pT=(e,t,n=20,i=new Set)=>au(e,t,n,i);function ou(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let r=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof r!="object"||r===null||!Array.isArray(r.events)))for(let a of r.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var Qn=async(e,t=20,n=!1)=>{let i=Zn.join(e,"history"),r;try{r=(await Xn.readdir(i)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{r=[]}let a=new Set,o=[],s=[],c=0,d=0,l=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(r.includes(p))try{h=ou(await Xn.readFile(Zn.join(i,p),"utf8"))}catch{h=new Set}for(let w of r){let v;try{v=await Xn.readFile(Zn.join(i,w),"utf8")}catch{continue}let E=w.slice(0,-6),k=au(E,v,t-o.length,h,n);c+=1,d+=k.checked_events,l+=k.unknown_event_count,u+=k.legacy_unknown_event_count,m+=k.actionable_unknown_event_count,f+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&a.add(E),o.push(...k.samples),n&&s.push(...k.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...a].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:s}:{}}};function Jg(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 Vg(e){try{return ou(await Xn.readFile(Zn.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Kg(e){return(e.item_id===ae||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Yg(e,t,n){let i=n[e.line-1]??"",r;try{r=JSON.parse(i)}catch{De(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return ru(r)!=="actionable_unknown"&&De(`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:iu("sha256").update(i).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function su(e,t,n){let i=t.events??[],r=+(t.all_actionable===!0)+ +(i.length>0);r===0&&De("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),r>1&&De("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&De("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let a=Jg(t.all_actionable===!0?(await Qn(e,0,!0)).actionable_events:i),o=await Vg(e),s=new Map;for(let m of a)if(Kg(m)||De(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await Xn.readFile(Zn.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{De(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=a.map(m=>Yg(m,o,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=iu("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="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 fT(e,t,n=50){return(await su(e,t,n)).plan}function Xg(e,t){let n=e.length>0;return n&&t&&De("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&&De("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:Zg(e),all_actionable:t}}function Zg(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),a=i===ae||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!a||!Number.isSafeInteger(r)||r<1)&&De(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function hT(e,t){let n=Xg(El(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Qg(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:Q(t,"planFingerprint")??Q(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:Q(t,"attributedAuthor")??Q(t,"attributed_author")??void 0,reviewer:Q(t,"reviewer"),reason:Q(t,"reason")})}async function Qg(e,t){let n=t.reviewer?.trim()??"",i=t.attributed_author?.trim()??"",r=t.reason?.trim()??"",a=await su(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:y.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&De("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||De("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()!==a.plan.plan_fingerprint)throw new g("Author acknowledgment selection changed after preview; no history was mutated.",y.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=a.completeCoordinates.filter(({disposition:l})=>a.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:y.NO_EFFECT,plan:a.plan};let s=await T(e),c=await dr({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:i}},message:r,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),d=a.plan.actionable_count>0&&a.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:y.PARTIAL_EFFECT}:{outcome:"effect",exit_code:y.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:o.length,...d,plan:a.plan,history_path:c.historyPath}}import{execFile as ey}from"node:child_process";import cu 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 du(e,t){return new Promise((n,i)=>{ey("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(r,a)=>{r?i(r):n(a)})})}function lu(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 vT(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(lu(n),!n)throw new RangeError("Source line range must use start:end.");return n}function ty(e){let t=new Map;for(let n of e.split(`
|
|
7
|
-
`)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function ny(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let a=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,s)=>o.localeCompare(s));n.set(r,a)}return n}async function iy(e){let t=cu.relative(e.workspaceRoot,cu.resolve(e.workspaceRoot,e.sourcePath)),n=await du(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await du(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:ty(n),commitItems:ny(i),available:!0}}function ry(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let a=r.source===t,o=a?r.target:r.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let s=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,a?r.kind:s.inverse??r.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function ay(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let a=t.shift(),o=a.kinds.length;r!==void 0&&o>=r||o>=e.maxDepth||(r=ry({current:a,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((a,o)=>a.nodes.join("\0").localeCompare(o.nodes.join("\0"))),i}function oy(e,t,n){let i=xl(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=ay({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(s=>[s.id,s]))}),a=r[0];if(!a)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(r.map(s=>s.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:a.nodes,kinds:a.kinds,alternative_decision_ids:o.slice(1)}}async function sy(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await iy({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function cy(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 dy(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function uu(e){lu(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 sy(e),i=dy(n),r=new Map;for(let a of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(a.item.id)),s=o.reduce((l,[,u])=>l+u,0),c=oy(a.item.id,e.corpus,t),d=cy({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});r.set(a.item.id,{score:s*100+a.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(a.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...a.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:a.item.value?.trim()||null,why_now:a.item.why_now?.trim()||null,outcome:a.item.outcome?.trim()||null,objective:a.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth: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]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var ei=["software-delivery","research","agent-evaluation","operations"];function mu(e,t,n,i,r){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:i,lifetime:"hold",enforcement:r,negative_control:{cases:[{observed:i,expected:"pass"},{observed:i+1,expected:"fail"}]}}}function Sr(e,t,n,i,r){let a=`preset-${e}`,o=r.map(c=>({id:`${a}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=o.map(c=>mu(`${c.id}-zero`,c.id,i,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:s,gates:[{id:`${a}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function xr(e,t){return e==="software-delivery"?Sr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Sr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Sr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Sr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function pu(e,t,n,i={}){return so(e,xr(t,n).declarations,i)}async function fu(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),i={...e,items:e.items.filter(r=>!n.has(r.status))};return await Promise.all(["files","tests","docs"].map(async r=>{let a={id:`derived-active-missing-${r}`,description:`Observed active items missing ${r} evidence.`,source:{kind:"links",link:r,state:"missing"}},o=(await oo(a,i)).value,s=mu(`${a.id}-ceiling`,a.id,t,o,"observe"),c=`active-missing-${r}`;return{id:c,population_size:i.items.length,scope:{kind:"active"},observed:o,declarations:{measurements:[a],assertions:[s],gates:[{id:`derived-${c}`,description:`Observe the accepted ${r} evidence baseline.`,assertion_ids:[s.id],triggers:["ci","scheduled"]}]}}}))}function hu(e,t,n={}){return so(e,{measurements:t.flatMap(i=>i.declarations.measurements),assertions:t.flatMap(i=>i.declarations.assertions),gates:t.flatMap(i=>i.declarations.gates)},n)}async function _u(e,t,n,i={}){let r=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==r)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${r}`);return kr(e,"assertion",{...t,enforcement:n},{...i,message:i.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import wu from"node:fs/promises";import{createRequire as ly}from"node:module";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]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function gu(e,t){let n=Ae.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ae.sep}`)&&!Ae.isAbsolute(n))return n.split(Ae.sep).join("/");let i=Ae.resolve(e),r=0xcbf29ce484222325n;for(let a=0;a<i.length;a+=1)r^=BigInt(i.charCodeAt(a)),r=BigInt.asUintN(64,r*0x100000001b3n);return`<external>/${r.toString(16).padStart(16,"0")}/${Ae.basename(Ae.dirname(e))}/package.json`}function uy(e){return e.includes(`${Ae.sep}.pnpm${Ae.sep}`)?"pnpm":e.includes(`${Ae.sep}node_modules${Ae.sep}`)?"npm":"other"}async function yu(e){try{let t=JSON.parse(await wu.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 co(e){try{return await wu.realpath(e)}catch{return Ae.resolve(e)}}async function vu(e,t,n=qe(import.meta.url,["../../.."])){let i=await co(t),r=await co(Ae.join(n,"package.json")),a=await yu(r),o=new Map;a!==void 0&&o.set(r,{version:a,path:gu(r,i),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=ly(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await co(l),m=await yu(u);if(m===void 0)continue;let f=u,p=o.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,_)=>h.localeCompare(_)));continue}o.set(f,{version:m,path:gu(u,i),layout:uy(u),consumers:[d.name]})}catch{}let s=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=a===void 0?[]:s.filter(d=>d.version!==a);return{host_version:a??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${a}:${d.version}:${d.consumers.join("+")}`)}}import lo from"node:fs/promises";import uo 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]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var bu=8388608,my=new Set(["resolved","failed"]),py=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mo(e){return py.find(t=>t.matches(e))?.kind}function ku(e){let t=new Map,n=0,i=0;return{entries:e.map(r=>{let a=Ye(r.agent_provenance)?r.agent_provenance:void 0;if(a===void 0||!jd(r).ok)return r;let o={},s=!1;for(let[d,l]of Object.entries(a)){let u=Ye(l)?mo(l.value):void 0;if(u===void 0){o[d]=l;continue}s=!0,i+=1;let m=r.agent_harness??"unknown",f=`${m}\0${d}\0${u}`,p=t.get(f)??{harness:m,dimension:d,kind:u,count:0};p.count+=1,t.set(f,p)}if(!s)return r;n+=1;let c={...r};return Object.keys(o).length===0?delete c.agent_provenance:c.agent_provenance=o,Fd(r,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:i,invalid_values:[...t.values()].sort((r,a)=>r.harness.localeCompare(a.harness)||r.dimension.localeCompare(a.dimension)||r.kind.localeCompare(a.kind))}}}async function Eu(e){let t=[];for(let n of await Su(e)??[])try{let i=await lo.readFile(uo.join(e,"history",n),"utf8");for(let r of i.split(`
|
|
8
|
-
`)){if(r.trim().length===0)continue;let a=xu(r);if(!(a===null||!Ye(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>Ye(o)&&mo(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Su(e){try{return(await lo.readdir(uo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function fy(e,t,n){let i;try{i=await lo.open(uo.join(e,"history",t),"r");let r=(await i.stat()).size,a=Math.min(r,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await i.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),d=s>=r,l=c.lastIndexOf(`
|
|
9
|
-
`)
|
|
10
|
-
`)){if(s.trim().length===0)continue;if(o>=i)return{eventsRead:o,truncated:!0};o+=1;let c=xu(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&wt(c.ts)){let d=new Date(c.ts).toISOString();(a.earliest_event_at===null||d<a.earliest_event_at)&&(a.earliest_event_at=d),(a.latest_event_at===null||d>a.latest_event_at)&&(a.latest_event_at=d)}hy(c,t,n)}return{eventsRead:o,truncated:!1}}function gy(e,t,n){return n?[...e.filter(i=>i.attempts>0&&i.successes===0).map(i=>`provenance_resolver_zero_success:${i.harness}:${i.dimension}:${i.resolver}:${String(i.attempts)}`),...t.map(i=>`provenance_value_domain_invalid:${i.harness}:${i.dimension}:${i.kind}:${String(i.count)}`)]:[]}async function Iu(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:bu,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},i=new Map,r=new Map,a=0,o=0,s=!1,c=await Su(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await fy(e,u,Math.max(0,bu-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=_y(m.content,i,r,t,a,n);if(a=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let d=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=o,n.events_read=a,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:gy(d,l,n.complete),events_read:a,truncated:s}}import yy 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]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function po(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Me(e.settings);if(n.ownership_enforcement==="strict")throw new g(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,y.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function wy(e){let t=await B(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new g(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);let n=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),i=n?e.readItem?await e.readItem(n):await ye(n,{schema:e.settings.schema}):null;if((i?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new g(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:i}}async function Ir(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await qa(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await yy.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await qa(e.historyPath)}catch(i){throw new AggregateError([n,i],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function Ru(e){let t=[...po({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await re(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let i=await wy({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(i),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(i)),t}finally{await 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]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function Au(e){let{subject:t,settings:n,operation:i,options:r}=e,a=await Ld(t.historyPath,t.id);if(a.raw===null)throw new g(`No history stream exists for ${t.id}.`,y.NOT_FOUND);if(a.entries.length===0)throw new g(`No history entries exist for ${t.id}; nothing to ${i.slice(8)}.`,y.USAGE);let o=t.located?await ye(t.located,{schema:n.schema}):null,s=z(r.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Wn(a.entries),loadedItem:o,author:s}),d=Wn(c.rewrittenEntries);if(!d.ok)throw new g(`${i} produced an invalid rewritten chain (${d.errors.join(", ")}).`,y.GENERIC_FAILURE);let l=c.changed&&!r.dryRun?await Ru({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:a.raw,currentItemRawBeforeLock:o?.raw??null,operation:i,author:s,force:r.force,itemDocument:o?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Ir({historyPath:t.historyPath,nextHistoryRaw:Nt(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>K({path:t.historyPath,scope:"project",op:`${i.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings:l})}(function(){try{var e=typeof window<"u"?window:typeof 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 Rr(e,t,n=25){let i=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,s)=>o.localeCompare(s)),r=new Set(i),a=t.filter(o=>{let s=Qc(o.status,e);return s!==void 0&&r.has(s)}).map(o=>o.id).sort((o,s)=>o.localeCompare(s));return{roleless_status_count:i.length,roleless_statuses:i.slice(0,n),roleless_statuses_truncated:i.length>n,affected_item_count:a.length,affected_item_ids:a.slice(0,n),affected_item_ids_truncated:a.length>n}}function Ar(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 Tu=8,fo=100;function $u(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function je(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function vy(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 ti(e,t){let n=je(e,t);return{...n,sample:n.sample.map(i=>vy(i))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(i=>typeof i=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function by(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 ky={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(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:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(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:ti(e.discovered,t),effective:ti(e.effective,t),loaded:ti(e.loaded,t),failed:je(e.failed,t),warnings:W(e.warnings,t),activation:{failed:je(n.failed,t),warnings:W(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:by(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:je(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:W(n.affected_item_ids,t),samples:je(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:W(e.item_unreadable,t),item_conflict_markers:je(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:je(e.history_conflict_markers,t),history_invalid_json:je(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:W(n.candidate_items,t),confirmed_items:W(n.confirmed_items,t),resolved_false_positive_items:W(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:W(e.drifted_items,t),merge_receipt_attributed_items:W(e.merge_receipt_attributed_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),version_skews:W(e.version_skews,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(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:W(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:W(e.stale_items_after,t),skipped:e.skipped})};function ho(e,t){let n=ky[e.name];return n?n(e.details,t):e.details}function Du(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 Ey(e){if(e.name==="extensions"&&e.status==="ok")return Du(e);let t=ho(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function _o(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(i=>n.has(i.warning))}function Sy(e){let t=W(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:Ey(n)})),warnings:t.sample,findings:_o(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 Cu(e){return e.details.skipped===!0}function xy(e){let t=W(e.warnings,8),n=e.checks.filter(Cu).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!Cu(i)).map(i=>({name:i.name,status:i.status,ok:i.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:_o(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 Iy(e,t,n){return t.full===!0?e:n?xy(e):t.brief===!0?Sy(e):{...e,checks:e.checks.map(i=>i.name==="extensions"&&i.status==="ok"?{...i,details:Du(i)}:i),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function go(e,t,n){let i=e.warning_count??e.warnings.length,r=e.warnings.slice(0,100),a={...e,warning_count:i,warning_limit:100,warnings_truncated:i>100,warnings:r,findings:_o(e,r)},o=Iy(a,t,n);return{...o,warning_count:i,warning_limit:100,warnings_truncated:i>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:i,warnings_truncated:i>o.warnings.length}}:{}}}import wo from"node:fs/promises";import ce from"node:path";import Ry from"node:readline/promises";import{stdin as Ay,stdout as Cr}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a0706e-7162-5cde-9f48-c5de9b2fbd8e")}catch{}})();var s$=["ask","add","skip","status"],Cy=["AGENTS.md","CLAUDE.md"],Ty=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],$y=8,vo=1,Dy="<!-- pm-cli:agent-guidance:start:",Oy=`<!-- pm-cli:agent-guidance:start:v${vo} -->`,yo="<!-- pm-cli:agent-guidance:end -->",ii="Add workflow guidance later: pm init --agent-guidance add";var Py=()=>Ry.createInterface({input:Ay,output:Cr});function pn(e,t){let n=ce.relative(e,t);return n.length===0?ce.basename(t):n.split(ce.sep).join("/")}function Ou(e){return e.endsWith(`
|
|
1
|
+
import{c as St,d as dn,e as ln,f as un,g as Nl,j as jl}from"./chunk-QFMJGQGO.js";import{a as Ll}from"./chunk-DFUTCKUF.js";import{i as Q,m as Za,x as Cl}from"./chunk-JNKRUCVZ.js";import{a as ja,c as zi,d as Wi,e as ed,g as td,h as Ua,i as nd,j as Kt,k as Yt,l as id,m as rd,n as Ha,o as sd,p as Xt,q as Zt,r as cd,s as dd,t as za}from"./chunk-Y6UYRMVG.js";import{a as qa}from"./chunk-SVOOGGAK.js";import{B as bd,C as Vi,D as kd,E as Wa,G as Ed,H as Sd,J as xd,K as Id,L as Ki,U as Yi}from"./chunk-6F6APBCX.js";import{K as Ml}from"./chunk-SFQKCA5K.js";import{A as Pl,I as eo,w as Dl,y as Qa,z as Ol}from"./chunk-PFBQOZPK.js";import{A as Cd,Aa as Ya,Ba as cn,Ca as kl,Da as El,Ea as Sl,Fa as Xa,H as Td,L as $d,M as Dd,N as Od,Q as dr,Sa as xl,Ta as Il,Xa as Rl,Ya as Al,ea as ur,fa as tl,ga as Va,ha as Bn,ja as Ka,k as Xi,na as pl,o as Hn,oa as fl,p as Rd,pa as hl,q as Ad,qa as _l,r as zn,ra as fr,ta as gl,ua as yl,va as wl,wa as Mt,xa as vl,ya as sn,za as bl}from"./chunk-NOKG4RFN.js";import{a as Yc,b as Vt,c as Fa,d as Xc,e as Zc,f as it,g as qi,h as Qc,i as wt}from"./chunk-2J7T2UCH.js";import{m as Jn,o as hr,v as Tl,y as $l}from"./chunk-KKRIFBSL.js";import{C as mr,E as ll,F as ge,G as ye,H as ul,I as pr,J as rt,K as at,O as ml,P as ot,a as Zi,c as Yd,j as nl,k as il,m as rl,n as al,o as Et,p as ol,q as sl,w as cl,x as dl}from"./chunk-5MCGYBOQ.js";import{$a as T,Aa as tn,Ba as Vd,Da as or,Ea as sr,Fa as qn,Ga as kt,Ha as Gn,Ia as Kd,Ja as cr,Ka as Nt,La as te,Ma as nn,Na as Xd,Oa as Ja,Pa as rn,Qa as an,Ra as on,Ta as Zd,Ua as Qd,Xa as je,_a as el,a as Pd,ab as lr,ba as z,ca as Hd,d as Re,da as Me,e as Ga,ea as zd,eb as ne,f as Ld,k as Qi,ka as Wd,l as Wn,la as Ba,m as Nd,ma as ir,n as er,na as en,o as Md,pa as rr,q as tr,qa as qd,r as nr,ra as Gd,t as jd,ta as Bd,u as $e,va as Jd,x as bt,y as Fd,ya as ar,z as Ud}from"./chunk-57HPXGOQ.js";import{b as Gt}from"./chunk-PC3R5CJV.js";import{a as se,c as Te,e as Ie,f as Ke,j as fe,k as ad,l as Gi,n as od}from"./chunk-MW77Q3AQ.js";import{$d as vd,Ac as Ji,Ba as Mc,Bb as Bc,Ca as Ot,Cb as Jc,Ea as jc,Fa as A,Ga as Fc,Ha as xe,Hc as hd,Ja as Hi,Ka as Uc,Kb as Vc,La as Pa,Lb as Pt,Ma as La,Mc as _d,Na,Nb as Ma,Nc as le,O as $c,Ob as Kc,Od as $,Pa as Hc,Pb as Jt,Pd as gd,Qa as zc,Qd as Qt,R as Dc,Rb as Je,Rd as vt,Sd as Lt,T as Oa,Ta as Wc,Tb as Ve,Xd as yd,Y as me,Z as Ge,_ as Oc,_d as wd,a as Ec,aa as Y,ae as re,bb as qc,d as Sc,da as Pc,e as xc,ec as ld,gc as Bi,hc as ud,ic as md,kb as Gc,kc as pd,o as Da,oa as Lc,pa as Nc,qa as H,sc as F,va as Un,wa as M,wc as K,xa as Be,ya as Ui,yc as Ne,za as Bt,zc as fd}from"./chunk-GP2WU43K.js";import{a as _r,b as Vn}from"./chunk-EGN2HFRU.js";import{A as g,B as Fn,C as D,D as yt,E as j,F as B,I as Z,a as Mi,d as ji,p as Ic,r as Rc,t as Ac,v as Cc,w as Fi,x as Tc,z as y}from"./chunk-JLXGRDTG.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]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},we=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ye=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 mn(e){try{return await e()}catch(t){throw t instanceof L?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function to(e){try{return await e()}catch(t){throw t instanceof we?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as gg}from"node:crypto";import yg 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 pn=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 Ul=1,jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],no=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],wg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],vg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,gr=30,yr=5e3,Hl=4,bg=50;function st(e,t){if(!vg.test(e))throw new L(`${t} must be a stable lowercase id`)}function kg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Kn(e){let t=wg.filter(r=>e[r]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function ro(e,t){return A(e)===A(t)}function zl(e,t){if(t.polarity==="equals")return ro(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let i=t.value;return e.every(r=>i.includes(r))}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 Wl(e){let t=Kn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>zl(i.observed,t)===(i.expected==="pass"))}function Eg(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,i=t.value;return!Array.isArray(n)||!Array.isArray(i)||i.some(r=>!n.includes(r))}return!ro(e.value,t.value)}function Sg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||A(e.scope)!==A(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Eg(Kn(e),Kn(t))||n[t.enforcement]<n[e.enforcement]||i}function xg(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,i=Number(t)+Number(n);if(e.field!==void 0&&i!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new L("items source equals/state requires field")}function Ig(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("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 L("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 L("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 L("dependency_kind source source_kind_state must be present or missing")}function Rg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("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 L("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 L("prose_edge_gap exemption selectors must not be empty")}}function ao(e){st(e.id,"measurement.id"),e.max_cost!==void 0&&kg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${no.join(", ")}`);let n=Reflect.get(t,"kind");if(!no.includes(n))throw new L(`measurement.source.kind must be one of ${no.join(", ")}`);let i=t;if(i.kind==="items"&&xg(i),i.kind==="dependency_kind"&&Ig(i),i.kind==="prose_edge_gap"&&Rg(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new L(`${i.kind} source requires field`);return i.kind==="provider"&&(st(i.provider,"provider source provider"),st(i.key,"provider source key")),e}function oo(e){if(st(e.id,"assertion.id"),st(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=Kn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`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 L("retired assertion requires retire_reason");e.scope.kind==="filter"&&st(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new L("assertion negative control requires pass and fail cases");if(!Wl(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function Ag(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)st(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!jt.includes(t))throw new L(`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 L(`gate provider policy trigger ${t} is invalid`)}}function ql(e){if(st(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)st(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${jt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!jt.includes(t))throw new L(`gate trigger must be one of ${jt.join(", ")}`);return e.provider_policy&&Ag(e.provider_policy),e}function fn(e){if(e.version!==Ul)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(ao(i),t.has(`measurement:${i.id}`))throw new L(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(oo(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){ql(i);let r=i.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(r.length>0)throw new L(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new L(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of Gl(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function so(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)so(n,t)}function Gl(e){let t=new Map,n=(i,r)=>{let a=t.get(i)??[];a.push(r),t.set(i,a)};for(let i of e.assertions)n(i.measurement_id,`assertion ${i.id}`),i.scope.kind==="filter"&&n(i.scope.measurement_id,`assertion ${i.id} scope`);for(let i of e.measurements){if(i.source.kind!=="derived")continue;let r=[];so(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function Cg(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let a=n.pop();if(i.has(a))continue;i.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&so(o.source.expression,n)}return r}function Yn(){return{version:Ul,measurements:[],assertions:[],gates:[]}}function Tg(e,t){let n=t.items.filter(i=>(e.statuses===void 0||e.statuses.includes(i.status))&&(e.types===void 0||e.types.includes(i.type))&&(e.tags===void 0||e.tags.every(r=>i.tags?.includes(r)))&&(e.field===void 0||(()=>{let r=i[e.field];if(e.state!==void 0){let a=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?a:!a}return ro(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function $g(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 Dg(e,t){let n=[],i=Oa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=Oa(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&$g(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Og(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 i=e[n];if(Array.isArray(i)){for(let r of i)if(typeof r=="string")t.push(r);else if(typeof r=="object"&&r!==null){let a=Reflect.get(r,"text");typeof a=="string"&&t.push(a)}}}return t}function Pg(e,t,n,i){return e.some(r=>r.holder_id.trim().toLowerCase()===t.toLowerCase()&&(r.target_id===void 0||r.target_id.trim().toLowerCase()===n.toLowerCase())&&(r.text_contains===void 0||i.toLowerCase().includes(r.text_contains.trim().toLowerCase())))}function io(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Lg(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(io(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(io(o.id,s));for(let s of Og(o)){let c=[...s.matchAll(r)].map(d=>d[0]);a+=c.length,i.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:a}}function Ng(e,t){let n=Lg(t.items),i=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=io(o.holder_id,d);if(n.linked_pairs.has(l)||Pg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],a=r.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function Mg(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 jg(e,t){let n=t.items.filter(i=>{let r=i[e.link],a=Array.isArray(r)&&r.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Fg(e,t){let n=e.source;return n.kind==="items"?Tg(n,t):n.kind==="dependency_kind"?Dg(n,t):n.kind==="prose_edge_gap"?Ng(n,t):n.kind==="history"?Mg(n,t):n.kind==="links"?jg(n,t):null}function Bl(e,t){return e.reduce((n,i)=>({units:n.units+i.units,items_scanned:n.items_scanned+i.items_scanned,history_entries:n.history_entries+i.history_entries,provider_calls:n.provider_calls+i.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function Ug(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,i)=>n+i,0);if(e==="subtract")return t.slice(1).reduce((n,i)=>n-i,t[0]);if(e==="multiply")return t.reduce((n,i)=>n*i,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,i)=>n/i,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Jl(e,t,n){let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o],o)}});return await Promise.all(a),i}async function Vl(e,t,n,i,r){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 s=await Kl(o,t,n,i,r);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[s.cost];return r.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await Jl(e.operands,Hl,o=>Vl(o,t,n,i,r));return{value:Ug(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Hg(e,t,n,i,r){ao(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await Vl(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Fg(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()-a},l=Bl([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new we(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${gg("sha256").update(A(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Kl(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let a=r.cache.get(e.id);if(a)return a;let o=Hg(e,t,n,i,r).catch(s=>{if(s instanceof Ye&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Ye(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function co(e,t,n=[e]){return Kl(e,t,n,[],{cache:new Map,charged:new Set})}function zg(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 Wg(e,t,n={}){oo(e);let i=Kn(e),r=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:i,distance:zg(t.value,i),verdict:r?"retired":zl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Wl(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function qg(e,t,n,i){let r=Cg(e,t);if(r.size===0)return;let a=e.provider_policy,o=a?.triggers[i];if(!a||!o)throw new we(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!s.has(d))throw new we(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new we(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new we(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new we(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Fl(e,t,n,i,r){try{return await co(n,i,r)}catch(a){if(a instanceof Ye){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new we(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function Yl(e,t,n,i){fn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new we(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new we(`assurance gate ${e} does not declare trigger ${i.trigger}`);qg(r,t,n,i.trigger);let a=await Jl(r.assertion_ids,Hl,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await Fl(r.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Wg(d,await Fl(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:r.id,tree_id:n.tree_id,trigger:i.trigger,dry_run:i.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Bl(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function wr(e){return yg.join(e,"assurance.json")}async function Xl(e){let t=await B(wr(e));return t===null?Yn():vr(t)}function vr(e){try{return fn(JSON.parse(e))}catch(t){throw new g("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.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 br(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Gg(e,t){e==="measurement"?ao(t):e==="assertion"?oo(t):ql(t)}async function Xn(e,t){let n=structuredClone(br(await Xl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Zl(e,t,n){let i=br(await Xl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function kr(e,t,n,i={}){Gg(t,n);let r=await T(e),a=z(i.author,r.author_default),o=await an({pmRoot:e,filePath:wr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Yn():vr(s),d=br(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Sg(d[l],n)){let m=n.authorization_decision;if(!m||!i.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),fn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
|
+
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function lo(e,t,n={}){let i=Yn();i.measurements=structuredClone(t.measurements),i.assertions=structuredClone(t.assertions),i.gates=structuredClone(t.gates),fn(i);let r=await T(e),a=z(n.author,r.author_default),o=await an({pmRoot:e,filePath:wr(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Yn():vr(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let _=m.find(w=>w.id===h.id);if(!_){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(A(_)!==A(h))throw new L(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,i.measurements,"measurement"),u(c.assertions,i.assertions,"assertion"),u(c.gates,i.gates,"gate"),fn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
+
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Ql(e,t,n,i={}){let r=await T(e),a=z(i.author,r.author_default),o=await an({pmRoot:e,filePath:wr(e),op:`assurance:${t}:remove`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Yn():vr(s);if(t==="measurement"){let u=Gl(c).get(n);if(u&&u.length>0)throw new L(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new L(`assurance assertion ${n} is referenced by gate`);let d=br(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new L(`assurance ${t} ${n} not found`);return d.splice(l,1),fn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
+
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function eu(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await T(e);await rn({pmRoot:e,op:"assurance:gate:verdict",author:z(n.author,i.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:gr,lockWaitMs:yr})}async function tu(e,t={}){let n=t.limit??bg;if(!Number.isInteger(n)||n<1||n>pn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${pn}`);return(await Me(nn(e),te)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}import{mkdir as Bg,readFile as Jg}from"node:fs/promises";import iu from"node:path";import{createHash as Vg}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]="a8daf042-f74c-5f51-b7e8-f8ff4fb8fe8e")}catch{}})();var uo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ru="sdk-workspace-transaction",au=/^[a-zA-Z0-9._-]+$/,ou=30,su=3e3;function _o(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!au.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function mo(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function go(e){return{pmRoot:mo(e.pmRoot,"Transaction pmRoot"),transactionId:_o(e.transactionId,"Transaction id"),author:mo(e.author,"Transaction author")}}function Sr(e,t,n){let i=e??t;if(!Number.isInteger(i)||i<=0)throw new TypeError(`${n} must be a positive integer`);return i}function cu(e,t){return iu.join(e,"transactions","sdk",`${t}.json`)}async function Xe(e,t){t.updatedAt=$();let n=cu(e,t.transactionId);await Bg(iu.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
|
|
5
|
+
`)}function Kg(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&Yg(e)}function Yg(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&au.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function Ft(e){return Object.assign(Object.create(null),e)}function du(e,t){try{let n=JSON.stringify(e,(i,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function po(e,t){return e===void 0?void 0:du(e,t)}function fo(e,t,n,i){let r=po(n,i);r===void 0?delete e[t]:e[t]=r}function nu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ho(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Xg(e,t){if(!ho(e.startedStepIds,t)||!ho(e.completedStepIds,t)||!nu(e.results)||!nu(e.compensationData))return!1;let n=e.startedStepIds,i=new Set(n),r=e.completedStepIds,a=new Set(r);return Object.keys(e.compensationData).some(o=>!i.has(o))||Object.keys(e.results).some(o=>!a.has(o))?!1:e.status==="committed"?t.every(o=>a.has(o)):!["compensated","abandoned"].includes(e.status??"")||a.size===0&&i.size===0}function Er(e,t){return new g(`Workspace transaction ${e} journal is invalid (${t})`,y.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function lu(e){return new g(`Workspace transaction ${e} journal does not match the supplied plan`,y.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function Zg(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((i,r)=>i===n[r])}function Qg(e,t,n){let i;try{i=JSON.parse(e)}catch{throw Er(t,"invalid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw Er(t,"expected an object");let r=i;if(!((r.schemaVersion===1||r.schemaVersion===2)&&r.transactionId===t))throw Er(t,"schema version or transaction id does not match the journal file");let a=r.stepIds;if(!Array.isArray(a)||!ho(a,a)||!Xg(r,a)||!Kg(r)||typeof r.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(r.status))throw Er(t,"invalid lifecycle, metadata, status or step ids");if(!Zg(r,a,n))throw lu(t);return{...r,results:Ft(r.results),compensationData:Ft(r.compensationData)}}async function ey(e,t,n,i,r){let a=r,o=a!==void 0;if(a?.status==="compensating"&&await yo(e,a),a===void 0||a.status==="compensated"){let s=$();a={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(a?.attempt??0)+1,createdAt:a?.createdAt??s,updatedAt:s,stepIds:i,startedStepIds:[],completedStepIds:[],results:Ft(),compensationData:Ft(),...e.recoveryData===void 0?{}:{recoveryData:du(e.recoveryData,"Transaction recovery data")}},await Xe(e.pmRoot,a),await ct(e,a,"prepared")}return{journal:a,recovered:o}}async function ty(e,t,n){try{await ny(t,e.steps),await Xe(e.pmRoot,t);let i=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let a of e.steps){if(i.has(a.id))continue;let o=await a.inspect(),s=po(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();fo(t.compensationData,a.id,c,`Step ${a.id} compensation data`),r.add(a.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>r.has(l)),await Xe(e.pmRoot,t);let d=await a.apply();s=po(d,`Step ${a.id} result`)}await ct(e,t,"step_applied",a.id),i.add(a.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>i.has(c)),fo(t.results,a.id,s,`Step ${a.id} result`),await Xe(e.pmRoot,t),await ct(e,t,"step_recorded",a.id)}return await ct(e,t,"committing"),t.status="committed",await Xe(e.pmRoot,t),await ct(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Ft(t.results)}}catch(i){if(i instanceof uo||t.status==="committed")throw i;try{await yo(e,t)}catch(r){throw new AggregateError([i,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw i}}async function xr(e,t,n){try{return Qg(await Jg(cu(e,t),"utf8"),t,n)}catch(i){if(i!==null&&typeof i=="object"&&"code"in i&&j(i))return;throw i}}async function ct(e,t,n,i){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...i===void 0?{}:{stepId:i}})}async function ny(e,t){let n=new Set,i=Ft();for(let r of t){let a=await r.inspect();a.state==="applied"&&(n.add(r.id),fo(i,r.id,a.result,`Step ${r.id} result`))}e.results=i,e.completedStepIds=t.map(r=>r.id).filter(r=>n.has(r))}async function yo(e,t){t.status="compensating",await Xe(e.pmRoot,t),await ct(e,t,"compensating");let n=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!i.has(r.id)&&!n.has(r.id))continue;let a;try{let o=(await r.inspect()).state;a=i.has(r.id)&&(o==="applied"||o==="pending"&&r.compensatePending===!0)}catch{a=i.has(r.id)}a&&(await ct(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),n.delete(r.id),i.delete(r.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>i.has(o)),delete t.results[r.id],delete t.compensationData[r.id],await Xe(e.pmRoot,t),await ct(e,t,"step_compensated",r.id)}t.status="compensated",await Xe(e.pmRoot,t),await ct(e,t,"compensated")}async function uu(e){let{pmRoot:t,transactionId:n,author:i}=go(e),r=Sr(e.lockTtlSeconds,ou,"Transaction lock TTL"),a=Sr(e.lockWaitMs,su,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let u=_o(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:i,steps:o,lockTtlSeconds:r,lockWaitMs:a},d=await re(t,ru,r,i,!1,!1,a);try{let l=await xr(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw mu(l);let u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Ft(l.results)};let m=await ey(c,n,i,s,l);return await ty(c,m.journal,u||m.recovered)}finally{await d()}}function mu(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,i=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new g(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,y.CONFLICT,{code:"transaction_abandoned",required:t?i:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[i]}:{}})}async function YC(e,t){let n=go({pmRoot:e,transactionId:t,author:"reader"});return xr(n.pmRoot,n.transactionId)}function iy(e){return Vg("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function XC(e){let t=go(e),n=mo(e.reason,"Abandonment reason"),i=e.supersededBy===void 0?void 0:_o(e.supersededBy,"Replacement transaction id");if(i===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let r=Sr(e.lockTtlSeconds,ou,"Transaction lock TTL"),a=Sr(e.lockWaitMs,su,"Transaction lock wait"),o=await re(t.pmRoot,ru,r,t.author,!1,!1,a);try{let s=await xr(t.pmRoot,t.transactionId);if(s===void 0)throw new g(`Transaction ${t.transactionId} was not found`,y.NOT_FOUND);if(s.status==="committed")throw new g(`Transaction ${t.transactionId} is committed and cannot be abandoned`,y.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(s.abandonment!==void 0&&s.abandonment.supersededBy!==i)throw mu(s);if(s.status==="abandoned")return s;let c=e.resolveSteps(structuredClone(s));if(JSON.stringify(c.map(d=>d.id))!==JSON.stringify(s.stepIds))throw lu(t.transactionId);if(s.abandonment===void 0){if(i!==void 0&&await xr(t.pmRoot,i)!==void 0)throw new g(`Replacement transaction ${i} already exists`,y.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...i===void 0?{}:{supersededBy:i}},await Xe(t.pmRoot,s)}return s.status!=="compensated"&&await yo({...e,...t,steps:c},s),await ry(s,t.pmRoot,r,a),s.status="abandoned",await Xe(t.pmRoot,s),s}finally{await o()}}async function ry(e,t,n,i){let r=iy(e);if((await Me(nn(t),te)).some(o=>o.op==="transaction_abandon"&&o.context?.transaction_id===e.transactionId&&o.context?.attempt===e.attempt&&o.context?.plan_digest===r))return;let a=e.abandonment;await rn({pmRoot:t,author:a.author,lockTtlSeconds:n,lockWaitMs:i,op:"transaction_abandon",message:a.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:r,...a.supersededBy===void 0?{}:{superseded_by:a.supersededBy}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var Zn={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ir={type:"array",minItems:1,maxItems:Pa,items:Zn},pu={...Ir,items:{...Zn,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},ay={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Ir])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:Zn,id:Zn}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:pu}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ir}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:pu,authors:Ir}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Pa,items:{type:"array",minItems:2,maxItems:2,items:Zn}}}}]}}},eT={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:Uc,items:ay}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function fu(e,t,n,i){let r=await Et(e).catch(()=>null);return r===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:hu(r,t,n,i)}function oy(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function hu(e,t,n=5,i=!1){let r=[],a=new Map,o=e.policies.filter(_=>_.rule.kind==="require_fields"),s=o.filter(_=>_.subject?.operations===void 0),c=new Set,d=0,l=0,u=0,m=0,f=0,p=Wc(e);for(let _ of t){let w=p({operation:"",author:"",before:_,after:_,completeness_only:!0});d+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(k=>c.add(k.policy_id));let v=w.decisions.filter(k=>!k.satisfied);if(v.length===0)continue;m+=1;let E=a.get(_.type)??{items:0,violations:0,missing_fields:0};E.items+=1;for(let k of v)u+=1,E.violations+=1,E.missing_fields+=k.missing_fields.length,k.effect==="refuse"&&(f+=1),r.length<n&&r.push({id:_.id,type:_.type,status:_.status,decision:k});a.set(_.type,E)}let h=i||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:oy(o.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(a),violations:r,violations_truncated:r.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...i?["validate_completeness_source_incomplete"]:[]]}}import sy 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]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function cy(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function yu(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new g("Policy definition must be valid JSON.",y.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("Policy definition must be an object.",y.USAGE);return t}async function dy(e,t){let n=M(process.cwd(),e.path);await ne(n);let i=await T(n);return{pmRoot:n,settings:i,author:z(t,i.author_default)}}function _u(e,t,n,i){if(e==="policy-mode")return Na({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let a=La(i.definition),o=Na({...n,policies:[...r,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
6
|
+
`)>rl)throw new g("Policy registry exceeds its byte ceiling.",y.USAGE);return o}async function gu(e,t,n,i){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:_u(e,t,await Et(i.pmRoot),n)};let r=await an({pmRoot:i.pmRoot,filePath:sy.join(i.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:i.author,message:n.message,lockTtlSeconds:i.settings.locks.ttl_seconds,lockWaitMs:i.settings.locks.wait_ms,mutate(a){let o=_u(e,t,al(a),n);return{raw:`${JSON.stringify(o,null,2)}
|
|
7
|
+
`,result:o}}});return{policy_result:!0,action:e,changed:r.changed,result:r.result}}async function ly(e,t,n){let i,r=await ml({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:i}),async mutate(a){let o=(await Et(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new g("--policy must name an approval rule.",y.USAGE);if(!o.rule.authors.includes(n.author))throw new g("This actor is not a declared approver.",y.CONFLICT);return await ol(n.pmRoot,a.metadata.id),i={policy_id:o.id,policy_fingerprint:Hc(o),content_fingerprint:zc(o,{...a.metadata,body:a.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:r.item.id,...i,warnings:r.warnings}}}function uy(e,t){let n=yu(t),i=La({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==i.id)throw new g("Policy id operand does not match definition.id.",y.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return i}async function vT(e,t,n={},i={}){if(!Hi.includes(e))throw new g("Unknown workflow policy action.",y.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:cy()};let r=await dy(i,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await Et(r.pmRoot)};if(e==="policy-put"){let l=uy(t,n.definition);return gu(e,l.id,{...n,definition:l},r)}if(!t?.trim())throw new g(`schema ${e} requires an operand.`,y.USAGE);if(["policy-remove","policy-mode"].includes(e))return gu(e,t,n,r);if(e==="policy-approve"){if(n.dryRun)throw new g("Use policy-check to preview; policy-approve records an approval.",y.USAGE);return ly(t,n,r)}let a=H(r.settings,F()),o=await ge(r.pmRoot,t,r.settings.id_prefix,r.settings.item_format,a.type_to_folder);if(!o)throw new g(`Item ${t} not found.`,y.NOT_FOUND);let{document:s}=await ye(o,{schema:r.settings.schema}),c={...s.metadata,body:s.body},d=n.definition===void 0?c:{...c,...yu(n.definition)};if(d.id!==c.id)throw new g("Policy preview cannot change the item id.",y.USAGE);return{policy_result:!0,action:e,changed:!1,result:await sl(r.pmRoot,await Et(r.pmRoot),{operation:"update",author:r.author,before:c,after:d,completeness_only:n.definition===void 0})}}import{createHash as vu}from"node:crypto";import Qn from"node:fs/promises";import ei 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 De(e,t){throw new g(e,y.USAGE,t)}var my="2026-07-15T06:22:12.276Z",py=Date.parse(my),fy=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],wu=e=>typeof e=="string"?e:"",bu=e=>{let t=e??{},n=wu(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(wu(t.ts))>=py);return fy[i][r]};function ku(e,t,n=20,i=new Set,r=!1){let a=[],o=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}d+=1;let h=bu(p);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,r&&h==="actionable_unknown"&&o.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:s.legacy_unknown+s.actionable_unknown>a.length,actionable_events:o}}var DT=(e,t,n=20,i=new Set)=>ku(e,t,n,i);function Eu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let r=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof r!="object"||r===null||!Array.isArray(r.events)))for(let a of r.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var ti=async(e,t=20,n=!1)=>{let i=ei.join(e,"history"),r;try{r=(await Qn.readdir(i)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{r=[]}let a=new Set,o=[],s=[],c=0,d=0,l=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(r.includes(p))try{h=Eu(await Qn.readFile(ei.join(i,p),"utf8"))}catch{h=new Set}for(let w of r){let v;try{v=await Qn.readFile(ei.join(i,w),"utf8")}catch{continue}let E=w.slice(0,-6),k=ku(E,v,t-o.length,h,n);c+=1,d+=k.checked_events,l+=k.unknown_event_count,u+=k.legacy_unknown_event_count,m+=k.actionable_unknown_event_count,f+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&a.add(E),o.push(...k.samples),n&&s.push(...k.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...a].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:s}:{}}};function hy(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 _y(e){try{return Eu(await Qn.readFile(ei.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function gy(e){return(e.item_id===te||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function yy(e,t,n){let i=n[e.line-1]??"",r;try{r=JSON.parse(i)}catch{De(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return bu(r)!=="actionable_unknown"&&De(`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:vu("sha256").update(i).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Su(e,t,n){let i=t.events??[],r=+(t.all_actionable===!0)+ +(i.length>0);r===0&&De("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),r>1&&De("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&De("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let a=hy(t.all_actionable===!0?(await ti(e,0,!0)).actionable_events:i),o=await _y(e),s=new Map;for(let m of a)if(gy(m)||De(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await Qn.readFile(ei.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{De(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=a.map(m=>yy(m,o,s.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=vu("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="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 OT(e,t,n=50){return(await Su(e,t,n)).plan}function wy(e,t){let n=e.length>0;return n&&t&&De("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&&De("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:vy(e),all_actionable:t}}function vy(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),a=i===te||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!a||!Number.isSafeInteger(r)||r<1)&&De(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function PT(e,t){let n=wy(Cl(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return by(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:Q(t,"planFingerprint")??Q(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:Q(t,"attributedAuthor")??Q(t,"attributed_author")??void 0,reviewer:Q(t,"reviewer"),reason:Q(t,"reason")})}async function by(e,t){let n=t.reviewer?.trim()??"",i=t.attributed_author?.trim()??"",r=t.reason?.trim()??"",a=await Su(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:y.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&De("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||De("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()!==a.plan.plan_fingerprint)throw new g("Author acknowledgment selection changed after preview; no history was mutated.",y.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=a.completeCoordinates.filter(({disposition:l})=>a.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:y.NO_EFFECT,plan:a.plan};let s=await T(e),c=await rn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:i}},message:r,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),d=a.plan.actionable_count>0&&a.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:y.PARTIAL_EFFECT}:{outcome:"effect",exit_code:y.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:o.length,...d,plan:a.plan,history_path:c.historyPath}}import{execFile as ky}from"node:child_process";import xu 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 Iu(e,t){return new Promise((n,i)=>{ky("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(r,a)=>{r?i(r):n(a)})})}function Ru(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 FT(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Ru(n),!n)throw new RangeError("Source line range must use start:end.");return n}function Ey(e){let t=new Map;for(let n of e.split(`
|
|
8
|
+
`)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function Sy(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let a=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,s)=>o.localeCompare(s));n.set(r,a)}return n}async function xy(e){let t=xu.relative(e.workspaceRoot,xu.resolve(e.workspaceRoot,e.sourcePath)),n=await Iu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await Iu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:Ey(n),commitItems:Sy(i),available:!0}}function Iy(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let a=r.source===t,o=a?r.target:r.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let s=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,a?r.kind:s.inverse??r.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function Ry(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let a=t.shift(),o=a.kinds.length;r!==void 0&&o>=r||o>=e.maxDepth||(r=Iy({current:a,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((a,o)=>a.nodes.join("\0").localeCompare(o.nodes.join("\0"))),i}function Ay(e,t,n){let i=$l(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=Ry({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(s=>[s.id,s]))}),a=r[0];if(!a)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(r.map(s=>s.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:a.nodes,kinds:a.kinds,alternative_decision_ids:o.slice(1)}}async function Cy(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await xy({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Ty(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 $y(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Au(e){Ru(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 Cy(e),i=$y(n),r=new Map;for(let a of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(a.item.id)),s=o.reduce((l,[,u])=>l+u,0),c=Ay(a.item.id,e.corpus,t),d=Ty({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});r.set(a.item.id,{score:s*100+a.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(a.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...a.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:a.item.value?.trim()||null,why_now:a.item.why_now?.trim()||null,outcome:a.item.outcome?.trim()||null,objective:a.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth: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]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var ni=["software-delivery","research","agent-evaluation","operations"];function Cu(e,t,n,i,r){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:i,lifetime:"hold",enforcement:r,negative_control:{cases:[{observed:i,expected:"pass"},{observed:i+1,expected:"fail"}]}}}function Rr(e,t,n,i,r){let a=`preset-${e}`,o=r.map(c=>({id:`${a}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=o.map(c=>Cu(`${c.id}-zero`,c.id,i,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:s,gates:[{id:`${a}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Ar(e,t){return e==="software-delivery"?Rr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Rr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Rr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Rr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Tu(e,t,n,i={}){return lo(e,Ar(t,n).declarations,i)}async function $u(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),i={...e,items:e.items.filter(r=>!n.has(r.status))};return await Promise.all(["files","tests","docs"].map(async r=>{let a={id:`derived-active-missing-${r}`,description:`Observed active items missing ${r} evidence.`,source:{kind:"links",link:r,state:"missing"}},o=(await co(a,i)).value,s=Cu(`${a.id}-ceiling`,a.id,t,o,"observe"),c=`active-missing-${r}`;return{id:c,population_size:i.items.length,scope:{kind:"active"},observed:o,declarations:{measurements:[a],assertions:[s],gates:[{id:`derived-${c}`,description:`Observe the accepted ${r} evidence baseline.`,assertion_ids:[s.id],triggers:["ci","scheduled"]}]}}}))}function Du(e,t,n={}){return lo(e,{measurements:t.flatMap(i=>i.declarations.measurements),assertions:t.flatMap(i=>i.declarations.assertions),gates:t.flatMap(i=>i.declarations.gates)},n)}async function Ou(e,t,n,i={}){let r=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==r)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${r}`);return kr(e,"assertion",{...t,enforcement:n},{...i,message:i.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Nu from"node:fs/promises";import{createRequire as Dy}from"node:module";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]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function Pu(e,t){let n=Ae.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ae.sep}`)&&!Ae.isAbsolute(n))return n.split(Ae.sep).join("/");let i=Ae.resolve(e),r=0xcbf29ce484222325n;for(let a=0;a<i.length;a+=1)r^=BigInt(i.charCodeAt(a)),r=BigInt.asUintN(64,r*0x100000001b3n);return`<external>/${r.toString(16).padStart(16,"0")}/${Ae.basename(Ae.dirname(e))}/package.json`}function Oy(e){return e.includes(`${Ae.sep}.pnpm${Ae.sep}`)?"pnpm":e.includes(`${Ae.sep}node_modules${Ae.sep}`)?"npm":"other"}async function Lu(e){try{let t=JSON.parse(await Nu.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 wo(e){try{return await Nu.realpath(e)}catch{return Ae.resolve(e)}}async function Mu(e,t,n=Ge(import.meta.url,["../../.."])){let i=await wo(t),r=await wo(Ae.join(n,"package.json")),a=await Lu(r),o=new Map;a!==void 0&&o.set(r,{version:a,path:Pu(r,i),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Dy(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await wo(l),m=await Lu(u);if(m===void 0)continue;let f=u,p=o.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,_)=>h.localeCompare(_)));continue}o.set(f,{version:m,path:Pu(u,i),layout:Oy(u),consumers:[d.name]})}catch{}let s=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=a===void 0?[]:s.filter(d=>d.version!==a);return{host_version:a??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${a}:${d.version}:${d.consumers.join("+")}`)}}import vo from"node:fs/promises";import bo 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]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var ju=8388608,Py=new Set(["resolved","failed"]),Ly=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ko(e){return Ly.find(t=>t.matches(e))?.kind}function Fu(e){let t=new Map,n=0,i=0;return{entries:e.map(r=>{let a=Ze(r.agent_provenance)?r.agent_provenance:void 0;if(a===void 0||!qd(r).ok)return r;let o={},s=!1;for(let[d,l]of Object.entries(a)){let u=Ze(l)?ko(l.value):void 0;if(u===void 0){o[d]=l;continue}s=!0,i+=1;let m=r.agent_harness??"unknown",f=`${m}\0${d}\0${u}`,p=t.get(f)??{harness:m,dimension:d,kind:u,count:0};p.count+=1,t.set(f,p)}if(!s)return r;n+=1;let c={...r};return Object.keys(o).length===0?delete c.agent_provenance:c.agent_provenance=o,Gd(r,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:i,invalid_values:[...t.values()].sort((r,a)=>r.harness.localeCompare(a.harness)||r.dimension.localeCompare(a.dimension)||r.kind.localeCompare(a.kind))}}}async function Uu(e){let t=[];for(let n of await Hu(e)??[])try{let i=await vo.readFile(bo.join(e,"history",n),"utf8");for(let r of i.split(`
|
|
9
|
+
`)){if(r.trim().length===0)continue;let a=zu(r);if(!(a===null||!Ze(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>Ze(o)&&ko(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Hu(e){try{return(await vo.readdir(bo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function Ny(e,t,n){let i;try{i=await vo.open(bo.join(e,"history",t),"r");let r=(await i.stat()).size,a=Math.min(r,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await i.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),d=s>=r,l=c.lastIndexOf(`
|
|
10
|
+
`),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await i?.close()}}function zu(e){try{let t=JSON.parse(e);return Ze(t)?t:null}catch{return null}}function My(e,t,n){let i=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(i===void 0)return;let r=Ze(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(r).forEach(([o,s])=>{if(!Ze(s))return;let c=ko(s.value);if(!c)return;let d=`${i}\0${o}\0${c}`,l=n.get(d)??{harness:i,dimension:o,kind:c,count:0};l.count+=1,n.set(d,l)}),!Ze(e.context))return;let a=e.context.agent_provenance_outcomes;Ze(a)&&Object.entries(a).forEach(([o,s])=>{if(!Ze(s)||typeof s.resolver!="string"||!Py.has(String(s.status)))return;let c=`${i}\0${o}\0${s.resolver}`,d=t.get(c)??{harness:i,dimension:o,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function jy(e,t,n,i,r,a){let o=r;for(let s of e.split(`
|
|
11
|
+
`)){if(s.trim().length===0)continue;if(o>=i)return{eventsRead:o,truncated:!0};o+=1;let c=zu(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&vt(c.ts)){let d=new Date(c.ts).toISOString();(a.earliest_event_at===null||d<a.earliest_event_at)&&(a.earliest_event_at=d),(a.latest_event_at===null||d>a.latest_event_at)&&(a.latest_event_at=d)}My(c,t,n)}return{eventsRead:o,truncated:!1}}function Fy(e,t,n){return n?[...e.filter(i=>i.attempts>0&&i.successes===0).map(i=>`provenance_resolver_zero_success:${i.harness}:${i.dimension}:${i.resolver}:${String(i.attempts)}`),...t.map(i=>`provenance_value_domain_invalid:${i.harness}:${i.dimension}:${i.kind}:${String(i.count)}`)]:[]}async function Wu(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:ju,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},i=new Map,r=new Map,a=0,o=0,s=!1,c=await Hu(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await Ny(e,u,Math.max(0,ju-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=jy(m.content,i,r,t,a,n);if(a=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let d=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=o,n.events_read=a,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:Fy(d,l,n.complete),events_read:a,truncated:s}}import Uy 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]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function Eo(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=je(e.settings);if(n.ownership_enforcement==="strict")throw new g(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,y.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function Hy(e){let t=await B(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new g(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);let n=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),i=n?e.readItem?await e.readItem(n):await ye(n,{schema:e.settings.schema}):null;if((i?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new g(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:i}}async function Cr(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await Ba(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Uy.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Ba(e.historyPath)}catch(i){throw new AggregateError([n,i],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function qu(e){let t=[...Eo({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await re(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let i=await Hy({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(i),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(i)),t}finally{await 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]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function Gu(e){let{subject:t,settings:n,operation:i,options:r}=e,a=await Hd(t.historyPath,t.id);if(a.raw===null)throw new g(`No history stream exists for ${t.id}.`,y.NOT_FOUND);if(a.entries.length===0)throw new g(`No history entries exist for ${t.id}; nothing to ${i.slice(8)}.`,y.USAGE);let o=t.located?await ye(t.located,{schema:n.schema}):null,s=z(r.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Gn(a.entries),loadedItem:o,author:s}),d=Gn(c.rewrittenEntries);if(!d.ok)throw new g(`${i} produced an invalid rewritten chain (${d.errors.join(", ")}).`,y.GENERIC_FAILURE);let l=c.changed&&!r.dryRun?await qu({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:a.raw,currentItemRawBeforeLock:o?.raw??null,operation:i,author:s,force:r.force,itemDocument:o?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Cr({historyPath:t.historyPath,nextHistoryRaw:Nt(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>K({path:t.historyPath,scope:"project",op:`${i.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings:l})}(function(){try{var e=typeof window<"u"?window:typeof 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 Tr(e,t,n=25){let i=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,s)=>o.localeCompare(s)),r=new Set(i),a=t.filter(o=>{let s=ad(o.status,e);return s!==void 0&&r.has(s)}).map(o=>o.id).sort((o,s)=>o.localeCompare(s));return{roleless_status_count:i.length,roleless_statuses:i.slice(0,n),roleless_statuses_truncated:i.length>n,affected_item_count:a.length,affected_item_ids:a.slice(0,n),affected_item_ids_truncated:a.length>n}}function $r(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 Ju=8,So=100;function Vu(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Fe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function zy(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 ii(e,t){let n=Fe(e,t);return{...n,sample:n.sample.map(i=>zy(i))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(i=>typeof i=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function Wy(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 qy={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(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:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(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:ii(e.discovered,t),effective:ii(e.effective,t),loaded:ii(e.loaded,t),failed:Fe(e.failed,t),warnings:W(e.warnings,t),activation:{failed:Fe(n.failed,t),warnings:W(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:Wy(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Fe(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:W(n.affected_item_ids,t),samples:Fe(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:W(e.item_unreadable,t),item_conflict_markers:Fe(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:Fe(e.history_conflict_markers,t),history_invalid_json:Fe(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:W(n.candidate_items,t),confirmed_items:W(n.confirmed_items,t),resolved_false_positive_items:W(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:W(e.drifted_items,t),merge_receipt_attributed_items:W(e.merge_receipt_attributed_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),version_skews:W(e.version_skews,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(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:W(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:W(e.stale_items_after,t),skipped:e.skipped})};function xo(e,t){let n=qy[e.name];return n?n(e.details,t):e.details}function Ku(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 Gy(e){if(e.name==="extensions"&&e.status==="ok")return Ku(e);let t=xo(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Io(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(i=>n.has(i.warning))}function By(e){let t=W(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:Gy(n)})),warnings:t.sample,findings:Io(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 Bu(e){return e.details.skipped===!0}function Jy(e){let t=W(e.warnings,8),n=e.checks.filter(Bu).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!Bu(i)).map(i=>({name:i.name,status:i.status,ok:i.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Io(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 Vy(e,t,n){return t.full===!0?e:n?Jy(e):t.brief===!0?By(e):{...e,checks:e.checks.map(i=>i.name==="extensions"&&i.status==="ok"?{...i,details:Ku(i)}:i),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function Ro(e,t,n){let i=e.warning_count??e.warnings.length,r=e.warnings.slice(0,100),a={...e,warning_count:i,warning_limit:100,warnings_truncated:i>100,warnings:r,findings:Io(e,r)},o=Vy(a,t,n);return{...o,warning_count:i,warning_limit:100,warnings_truncated:i>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:i,warnings_truncated:i>o.warnings.length}}:{}}}import Co from"node:fs/promises";import ce from"node:path";import Ky from"node:readline/promises";import{stdin as Yy,stdout as Dr}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a0706e-7162-5cde-9f48-c5de9b2fbd8e")}catch{}})();var I$=["ask","add","skip","status"],Xy=["AGENTS.md","CLAUDE.md"],Zy=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Qy=8,To=1,ew="<!-- pm-cli:agent-guidance:start:",tw=`<!-- pm-cli:agent-guidance:start:v${To} -->`,Ao="<!-- pm-cli:agent-guidance:end -->",ai="Add workflow guidance later: pm init --agent-guidance add";var nw=()=>Ky.createInterface({input:Yy,output:Dr});function hn(e,t){let n=ce.relative(e,t);return n.length===0?ce.basename(t):n.split(ce.sep).join("/")}function Yu(e){return e.endsWith(`
|
|
11
12
|
`)?e:`${e}
|
|
12
|
-
`}function
|
|
13
|
+
`}function iw(e){return e.includes(`\r
|
|
13
14
|
`)?`\r
|
|
14
15
|
`:`
|
|
15
|
-
`}function
|
|
16
|
+
`}function Xu(e){let t=e.indexOf(ew);if(t===-1)return null;let n=e.indexOf(Ao,t);return n===-1?null:{start_index:t,end_index:n+Ao.length}}function rw(e){return Xu(e)!==null}function aw(e,t="<your project test command>"){return[tw,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start atomically: `pm claim <id> --start`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Ao,""].join(e)}function Zu(e,t="<your project test command>"){let n=iw(e),i=aw(n,t),r=Xu(e);if(r){let s=e.slice(r.end_index),c=s.startsWith(`\r
|
|
16
17
|
`)?s.slice(2):s.startsWith(`
|
|
17
|
-
`)?s.slice(1):s,d=
|
|
18
|
+
`)?s.slice(1):s,d=Yu(`${e.slice(0,r.start_index)}${i}${c}`);return{next_content:d,changed:d!==e}}let a=e.length===0?"":e.endsWith(`
|
|
18
19
|
`)?`
|
|
19
20
|
`:`
|
|
20
21
|
|
|
21
|
-
`,o=
|
|
22
|
+
`,o=Yu(`${e}${a}${i}`);return{next_content:o,changed:o!==e}}async function Qu(e){if(await D(ce.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Co.readFile(ce.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=ow(t);if(n===void 0)return"<your project test command>";let i=n.packageManager?.split("@")[0];return i==="pnpm"?"pnpm test":i==="bun"?"bun run test":i==="yarn"?"yarn test":i==="npm"?"npm test":await D(ce.join(e,"pnpm-lock.yaml"))?"pnpm test":await D(ce.join(e,"bun.lock"))||await D(ce.join(e,"bun.lockb"))?"bun run test":await D(ce.join(e,"yarn.lock"))?"yarn test":"npm test"}function ow(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function sw(e,t){let n=ce.dirname(e);return ce.basename(e)==="pm"&&ce.basename(n)===".agents"?ce.dirname(n):ce.resolve(t,e)}function cw(e,t){let n=e.find(r=>ce.basename(r.file_path)==="AGENTS.md"&&r.exists);if(n)return n.file_path;let i=e.find(r=>r.exists);return i?i.file_path:ce.join(t,"AGENTS.md")}function dw(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function lw(e){let t=nw();try{Dr.write(`
|
|
22
23
|
Agent guidance check
|
|
23
|
-
`),
|
|
24
|
-
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return
|
|
25
|
-
`),Hy(n,!0)}finally{t.close()}}function Mu(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:vo,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,i)=>n.localeCompare(i)):[]}}async function ju(e){let t=[],n=await Nu(e);for(let i of Cy){let r=ce.join(e,i),a=await D(r);if(!a){t.push({file_path:r,exists:a,has_guidance:!1,has_marker:!1});continue}let o=await wo.readFile(r,"utf8"),s=o.toLowerCase(),c=Ty.filter(l=>s.includes(l)),d=Ny(o);t.push({file_path:r,exists:a,has_guidance:d||c.length>=$y,has_marker:d,outdated:d&&Lu(o,n).changed})}return t}function Ft(e,t){e.includes(t)||e.push(t)}function Wy(e,t){let n=Mu(e),i=JSON.stringify(n)!==JSON.stringify(t);return i&&(e.agent_guidance=t),{changed:i,state:t}}async function Fu(e,t=ce.dirname(e)){let n=await D(e)?await wo.readFile(e,"utf8"):"",i=Lu(n,await Nu(t));return i.changed?(await Z(e,i.next_content),{changed:!0,warnings:await K({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function qy(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>pn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>pn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>pn(e.projectRoot,t.file_path))}}async function Gy(e,t,n){return e?await ju(n):t}function ni(e,t,n){e.state={...e.state,...n,template_version:vo,last_checked_files:t}}async function Uu(e,t){if(t.presentBefore)return;let n=await Fu(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function By(e,t){t||(e.warnings.push("agent_guidance:missing"),Ft(e.nextSteps,ii))}function Jy(e,t){e.skipped=!0,ni(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ft(e.nextSteps,ii)}async function Vy(e,t){await Uu(e,t),ni(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Ky(e,t){e.state.declined&&ni(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Yy(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ft(e.nextSteps,ii)}async function Xy(e,t){if(e.prompted=!0,await zy(t.targetRelativePath)){await Uu(e,t),ni(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ni(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ft(e.nextSteps,ii)}function Zy(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ft(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ft(e.nextSteps,ii)}async function Qy(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(By(n,t.presentBefore),n):t.mode==="skip"?(Jy(n,t.checkedFiles),n):t.mode==="add"?(await Vy(n,t),n):t.presentBefore?(Ky(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Yy(n),n):t.interactive?(await Xy(n,t),n):(Zy(n),n)}async function Hu(e){let t=Fy(e.pm_root,e.cwd),n=await ju(t),i=Uy(n,t),r=pn(t,i),a=n.map(l=>pn(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await Qy(Mu(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:i,targetRelativePath:r,checkedFiles:a,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let l of n.filter(u=>u.outdated)){let u=await Fu(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=Wy(e.settings,s.state);n=await Gy(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>pn(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Ft(s.nextSteps,"pm init --agent-guidance add")),{summary:qy({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:r,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8289336-e833-5617-9a32-0a21f28f294e")}catch{}})();function ri(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,i,r,a,o,s]=t,c=s.split(":")[0].replace(i==="min"?"required=":"allowed=",""),d=r==="invalid"?`a valid pm_${i}_version instead of ${c}`:`pm ${i==="min"?">=":"<="} ${c}`;return n?`Package ${o} is disabled and requires ${d} before activation. After satisfying the bound, run ${le(["package","activate",o,`--${a}`])}.`:`Package ${o} requires ${d}. Use a compatible host or package version, or keep it disabled with ${le(["package","deactivate",o,`--${a}`])}.`}import ht from"node:fs/promises";import be from"node:path";import ai from"node:fs/promises";import{createHash as ew}from"node:crypto";import Wu 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]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();var bo=new Set([void 0,...Ad]),qu=11,tw="history-drift-cache.json";function Gu(e){return Wu.join(e,"runtime",tw)}async function nw(e){try{let t=await ai.readFile(Gu(e),"utf8"),n=JSON.parse(t);return n.version!==qu||n.history_item_hash_version!==tr||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(i=>typeof i.chain_ok!="boolean"||typeof i.latest_hash_comparable!="boolean"||!bo.has(i.hash_algorithm)||!en.includes(i.item_hash_version)&&i.version_skew!==!0||i.chain_ok&&i.version_skew!==!0&&en.includes(i.item_hash_version)&&!i.latest_hash_comparable)?null:n}catch{return null}}function Bu(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Ju(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[ae]:[]])].sort((n,i)=>n.localeCompare(i));return{...e,driftedItems:t}}async function iw(e,t,n,i,r){let a=cr(e),o;try{o=await ai.stat(a)}catch(d){return j(d)||r.unreadableStreams.push(ae),!1}let s=r.missingStreams.length,c=await Vu({itemId:ae,historyPath:a,stat:o,cached:t[ae],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.versionSkew&&r.versionSkews.push(ae),c.verification.chainOk||r.chainMismatches.push(ae),n[ae]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(r.missingStreams.splice(s),c.cacheDirty)}function rw(e){return!bo.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!en.includes(e.item_hash_version)}async function aw(e){let t=await ai.readFile(e,"utf8"),n=ew("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let i=[],r=null;for(let m of t.split(/\r?\n/)){let f=m.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(p),r=p.after_hash}if(!r)return null;let a=bt(i),o=i.some(rw),s=i[i.length-1],c=bo.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&en.includes(d),u=l?d:a.item_hash_version;return{latestAfterHash:r,hashAlgorithm:c?Re(s.hash_algorithm):void 0,identityDiscontinuities:Cd(i),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??tr}}function ow(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function zu(e,t,n){try{return await aw(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function sw(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function Vu(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(ow(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await zu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await zu(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!sw(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&en.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Ku(e,t,n,i){let r,a;try{r=Ot(e,t.id),a=await ai.stat(r)}catch(d){return(j(d)?i.missingStreams:i.unreadableStreams).push(t.id),!1}let o=await Vu({itemId:t.id,historyPath:r,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:i});if(!o.verification)return o.cacheDirty;o.verification.identityDiscontinuities.length>0&&(i.identityDiscontinuities??=[]).push(...o.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),o.verification.versionSkew&&i.versionSkews.push(t.id),o.verification.chainOk||i.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,version_skew:o.verification.versionSkew,latest_hash_comparable:o.verification.latestHashComparable,item_hash_version:o.verification.itemHashVersion,hash_algorithm:o.verification.hashAlgorithm};let{body:s,...c}=t;return o.verification.latestHashComparable&&(Ud({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||i.hashMismatches.push(t.id)),o.cacheDirty}async function cw(e,t){if(!(t.unreadableStreams.includes(ae)||t.chainMismatches.includes(ae)||t.versionSkews.includes(ae)))try{let n=await Gd(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ae)}}async function Yu(e,t){let n=Bu();return await Ku(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Ju(n)}async function Ut(e,t,n={}){let i=Bu(),r=(await nw(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:r,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await Ku(e,l,c,i)&&(o=!0);let d=await iw(e,r,a,s,i);if(o||=d,await cw(e,i),o||Object.keys(r).length!==Object.keys(a).length){let l=Gu(e);try{await ai.mkdir(Wu.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:qu,history_item_hash_version:tr,entries:a}))}catch{}}return Ju(i)}import fn from"node:fs/promises";import Tr 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]="6b4ef85f-d844-53e3-ba32-08b95377584a")}catch{}})();function Xu(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:i,owner:r,created_at:a,ttl_seconds:o}=n;return typeof i!="string"||typeof r!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:i,owner:r,created_at:a,ttl_seconds:o,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function dw(e,t,n){let i=Xu(t);if(i===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 r=Date.parse(i.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-r,o=Math.floor(a/1e3),s=a>i.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function Zu(e,t,n){let i=dw(e,t,n);if(i.detail!=="active")return i;let r=Xu(t),a=await md(r);return a==="unknown"?i:{detail:a==="dead"?"owner_dead":"active",entry:{...i.entry,owner_state:a,pid:r.pid,...a==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function lw(e,t,n){let i=await pd(e,"gc");if(i===null)return!1;try{let r;try{r=await fn.readFile(e,"utf8")}catch(a){if(j(a))return!0;throw a}if(r!==t)return!1;n&&await fd(e,t);try{await fn.unlink(e)}catch(a){if(!j(a))throw a}return!0}finally{await i()}}function uw(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 Qu(e,t){let n=t??Date.now(),i=Tr.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await fn.readdir(i)).filter(o=>o.endsWith(".lock")).sort()}catch(o){if(j(o))return r;throw o}for(let o of a){let s;try{s=await fn.readFile(Tr.join(i,o),"utf8")}catch(l){if(j(l))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c,entry:d}=await Zu(o,s,n);uw(r,c,d)}return r}async function mw(e,t,n,i,r,a,o){if(!t.dryRun){try{if(!await lw(n,a,o.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${r}`),e.retained.push(i),e.entries.push(o);return}}catch{e.warnings.push(`lock_remove_failed:${r}`),e.retained.push(i),e.entries.push(o);return}if(t.hooks?.onWrite){let s=await t.hooks.onWrite(n);e.warnings.push(...s)}}e.removed.push(i),e.entries.push(o)}async function em(e,t){let{hooks:n}=t,i=t.now??Date.now(),r=Tr.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},o;try{o=(await fn.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(s){if(j(s))return a;throw s}for(let s of o){a.scanned+=1;let c=Tr.join(r,s),d=`locks/${s}`;if(n?.onRead){let m=await n.onRead(c);a.warnings.push(...m)}let l;try{l=await fn.readFile(c,"utf8")}catch(m){if(j(m)){a.scanned-=1;continue}a.warnings.push(`lock_unreadable:${s}`),a.retained.push(d),a.entries.push({file:s,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await Zu(s,l,i);if(u.detail==="unparseable_json"){a.warnings.push(`lock_unparseable:${s}`),a.retained.push(d),a.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){a.warnings.push(`lock_invalid_timestamp:${s}`),a.retained.push(d),a.entries.push(u.entry);continue}if(u.detail==="active"){a.retained.push(d),a.entries.push(u.entry);continue}await mw(a,t,c,d,s,l,u.entry)}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]="0e576e9d-5aa3-5d54-8acf-23e4f18b432f")}catch{}})();var pw=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 ko(e){if(typeof e!="string")return;let t=e.trim();for(let n of pw)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Eo(e){let t={};for(let n of e){let i=ko(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function tm(e){return Object.values(Eo(e))}import Sn from"node:fs/promises";import Oe 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]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var fw=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function hn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(qi(t.extensionName));for(let _ of t.extensionNames??[])n.add(qi(_));let i=_=>n.size===0||n.has(qi(_)),r=(_,w)=>nm(_.filter(v=>i(v.name)).map(w)),a=(_,w)=>nm(_.filter(v=>i(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,f=a(o.relationship_kinds??[],_=>_.definitions.map(w=>w.kind)),p=u.overrides.filter(_=>i(_.name)&&((_.commands?.length??0)>0||_.resultDiscriminator!==void 0)).map(_=>({format:_.format,commands:[..._.commands??[]],result_discriminator:_.resultDiscriminator!==void 0})).sort((_,w)=>_.format.localeCompare(w.format)),h=r(o.assurance_providers??[],_=>_.definition.id);return{capabilities:ad(e,t),commands:r(o.commands,_=>_.command),command_overrides:r(s.overrides,_=>_.command),command_handlers:r(s.handlers,_=>_.command),hooks:fw.filter(([_])=>m[_].some(w=>i(w.name))).map(([,_])=>_),flag_commands:r(o.flags,_=>_.target_command),item_types:a(o.item_types,_=>_.types.map(w=>w.name)),item_fields:a(o.item_fields,_=>_.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:a(o.migrations,_=>typeof _.definition.id=="string"?[_.definition.id]:[]),profiles:r(o.profiles,_=>_.profile.name),importers:r(o.importers,_=>_.importer),exporters:r(o.exporters,_=>_.exporter),search_providers:r(o.search_providers,_=>_.definition.name),vector_store_adapters:r(o.vector_store_adapters,_=>_.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:r(c.overrides,_=>_.command),service_overrides:r(l.overrides,_=>_.service),renderer_overrides:r(u.overrides,_=>_.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:d.overrides.filter(_=>i(_.name)).length,preflight_ownership:d.overrides.filter(_=>i(_.name)).map(_=>({commands:[..._.commands??[]]}))}}function nm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import rv from"node:path";import{mkdir as av}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]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var hw=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function _w(e){let t=hw.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function gw(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function im(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,i=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let c=_w(s);if(c===void 0)continue;let d=r.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<i&&d.examples.push(s),r.set(c,d)}let a=[];for(let[o,s]of r.entries()){if(s.count<n)continue;let c=gw(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:qc(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as fm}from"node:crypto";import gn from"node:fs/promises";import yn from"node:path";import{mkdir as yw,readFile as ww}from"node:fs/promises";import sm 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]="d913251a-fc99-5767-b19d-ae9473adc138")}catch{}})();var So=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},vw="sdk-workspace-transaction",bw=/^[a-zA-Z0-9._-]+$/,kw=30,Ew=3e3;function cm(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!bw.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function rm(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function Sw(e){return{pmRoot:rm(e.pmRoot,"Transaction pmRoot"),transactionId:cm(e.transactionId,"Transaction id"),author:rm(e.author,"Transaction author")}}function am(e,t,n){let i=e??t;if(!Number.isInteger(i)||i<=0)throw new TypeError(`${n} must be a positive integer`);return i}function dm(e,t){return sm.join(e,"transactions","sdk",`${t}.json`)}async function St(e,t){t.updatedAt=$();let n=dm(e,t.transactionId);await yw(sm.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
|
|
26
|
-
`)}function xw(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Ht(e){return Object.assign(Object.create(null),e)}function Iw(e,t){try{let n=JSON.stringify(e,(i,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function xo(e,t){return e===void 0?void 0:Iw(e,t)}function Io(e,t,n,i){let r=xo(n,i);r===void 0?delete e[t]:e[t]=r}function om(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ro(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Rw(e,t){if(!Ro(e.startedStepIds,t)||!Ro(e.completedStepIds,t)||!om(e.results)||!om(e.compensationData))return!1;let n=e.startedStepIds,i=new Set(n),r=e.completedStepIds,a=new Set(r);return Object.keys(e.compensationData).some(o=>!i.has(o))||Object.keys(e.results).some(o=>!a.has(o))?!1:e.status==="committed"?t.every(o=>a.has(o)):e.status!=="compensated"||a.size===0&&i.size===0}function $r(e,t){return new g(`Workspace transaction ${e} journal is invalid (${t})`,y.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function Aw(e){return new g(`Workspace transaction ${e} journal does not match the supplied plan`,y.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the exact plan that started this transaction, or start a new transaction with a different id.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","Pass --transaction-id <new-id> (or a new transactionId over MCP) to commit the changed plan as its own transaction.","Run pm ops gc --scope transactions --dry-run to inspect abandoned journals before pruning them."]})}function Cw(e,t,n){let i;try{i=JSON.parse(e)}catch{throw $r(t,"invalid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw $r(t,"expected an object");let r=i;if(!(r.schemaVersion===1&&r.transactionId===t))throw $r(t,"schema version or transaction id does not match the journal file");let a=r.stepIds;if(!Array.isArray(a)||!Ro(a,a)||!Rw(r,a)||!xw(r)||typeof r.status!="string"||!["applying","compensating","compensated","committed"].includes(r.status))throw $r(t,"invalid lifecycle, metadata, status or step ids");if(!(r.status==="compensated"||a.length===n.length&&a.every((o,s)=>o===n[s])))throw Aw(t);return{...r,results:Ht(r.results),compensationData:Ht(r.compensationData)}}async function Tw(e,t,n,i,r){let a=r,o=a!==void 0;if(a?.status==="compensating"&&await lm(e,a),a===void 0||a.status==="compensated"){let s=$();a={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(a?.attempt??0)+1,createdAt:a?.createdAt??s,updatedAt:s,stepIds:i,startedStepIds:[],completedStepIds:[],results:Ht(),compensationData:Ht()},await St(e.pmRoot,a),await st(e,a,"prepared")}return{journal:a,recovered:o}}async function $w(e,t,n){try{await Ow(t,e.steps),await St(e.pmRoot,t);let i=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let a of e.steps){if(i.has(a.id))continue;let o=await a.inspect(),s=xo(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();Io(t.compensationData,a.id,c,`Step ${a.id} compensation data`),r.add(a.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>r.has(l)),await St(e.pmRoot,t);let d=await a.apply();s=xo(d,`Step ${a.id} result`)}await st(e,t,"step_applied",a.id),i.add(a.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>i.has(c)),Io(t.results,a.id,s,`Step ${a.id} result`),await St(e.pmRoot,t),await st(e,t,"step_recorded",a.id)}return await st(e,t,"committing"),t.status="committed",await St(e.pmRoot,t),await st(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Ht(t.results)}}catch(i){if(i instanceof So||t.status==="committed")throw i;try{await lm(e,t)}catch(r){throw new AggregateError([i,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw i}}async function Dw(e,t,n){try{return Cw(await ww(dm(e,t),"utf8"),t,n)}catch(i){if(i!==null&&typeof i=="object"&&"code"in i&&j(i))return;throw i}}async function st(e,t,n,i){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...i===void 0?{}:{stepId:i}})}async function Ow(e,t){let n=new Set,i=Ht();for(let r of t){let a=await r.inspect();a.state==="applied"&&(n.add(r.id),Io(i,r.id,a.result,`Step ${r.id} result`))}e.results=i,e.completedStepIds=t.map(r=>r.id).filter(r=>n.has(r))}async function lm(e,t){t.status="compensating",await St(e.pmRoot,t),await st(e,t,"compensating");let n=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!i.has(r.id)&&!n.has(r.id))continue;let a;try{let o=(await r.inspect()).state;a=i.has(r.id)&&(o==="applied"||o==="pending"&&r.compensatePending===!0)}catch{a=i.has(r.id)}a&&(await st(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),n.delete(r.id),i.delete(r.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>i.has(o)),delete t.results[r.id],delete t.compensationData[r.id],await St(e.pmRoot,t),await st(e,t,"step_compensated",r.id)}t.status="compensated",await St(e.pmRoot,t),await st(e,t,"compensated")}async function um(e){let{pmRoot:t,transactionId:n,author:i}=Sw(e),r=am(e.lockTtlSeconds,kw,"Transaction lock TTL"),a=am(e.lockWaitMs,Ew,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let u=cm(l.id,"Transaction step id");if(u!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:i,steps:o,lockTtlSeconds:r,lockWaitMs:a},d=await re(t,vw,r,i,!1,!1,a);try{let l=await Dw(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Ht(l.results)};let m=await Tw(c,n,i,s,l);return await $w(c,m.journal,u||m.recovered)}finally{await 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]="09d88765-6283-5287-b293-43300251833f")}catch{}})();function ct(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function hm(e){let t=ct(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function _m(e,t){let n=Co(e),i=ct(t,"migrationScope");return`auto-${fm("sha256").update(JSON.stringify({scope:i,request:n})).digest("hex").slice(0,20)}`}function Co(e){let t=e.kind==="rename-type"?{kind:e.kind,from:ct(e.from,"source"),to:ct(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:se(ct(e.from,"source")),to:se(ct(e.to,"target")),...e.type===void 0?{}:{type:ct(e.type,"type")}}:{kind:e.kind,from:se(ct(e.from,"source")),to:se(ct(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Pw(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Lw(e,t,n){let i=Ie(t.schema),r=Pw(n);return Ve(e,i.files[r],Te[r])}function gm(e,t){return yn.join(e,"transactions","schema",`${t}-plan.json`)}function Dr(e){return e.length===0?null:JSON.parse(e)}async function _n(e){let t=await B(e);return{exists:t!==null,raw:t??""}}async function ym(e,t){t.exists?await Z(e,t.raw):await gn.rm(e,{force:!0})}function Nw(e,t,n){let i=tt(e),r=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return yt(i);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);i.definitions.push({...i.definitions[r],name:t.to})}else r>=0&&i.definitions.splice(r,1);return yt(i)}function Mw(e,t,n){let i=Kt(e),r=i.fields.findIndex(o=>o.key===t.from),a=i.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(a>=0)return Yt(i);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=i.fields[r];i.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&i.fields.splice(r,1);return Yt(i)}function jw(e,t,n){let i=Xt(e),r=i.statuses.findIndex(o=>o.id===t.from),a=i.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(a>=0)return Zt(i);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);i.statuses.push({...i.statuses[r],id:t.to})}else r>=0&&i.statuses.splice(r,1);return Zt(i)}function Fw(e,t,n){return t.kind==="rename-type"?Nw(e,t,n):t.kind==="rename-field"?Mw(e,t,n):jw(e,t,n)}function xt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function To(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function wn(e){return Array.isArray(e)?e.map(t=>To(t)).filter(t=>t!==void 0):[]}function Uw(e,t){for(let n of wn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(i=>xt(i,t)));for(let n of wn(e.type_workflows))n.type=xt(n.type,t)}function Hw(e,t){for(let i of wn(e.definitions))i.default_status=xt(i.default_status,t);let n=To(e.workflow);if(n)for(let[i,r]of Object.entries(n))n[i]=xt(r,t);for(let i of wn(e.type_workflows))Array.isArray(i.allowed_transitions)&&(i.allowed_transitions=i.allowed_transitions.map(r=>Array.isArray(r)?r.map(a=>xt(a,t)):r))}function zw(e,t){for(let n of wn(e.definitions)){for(let i of["required_create_fields","required_create_repeatables"])Array.isArray(n[i])&&(n[i]=n[i].map(r=>xt(r,t)));for(let i of["options","command_option_policies"])for(let r of wn(n[i])){let a=i==="options"?"key":"option";r[a]=xt(r[a],t)}}}function Ww(e,t){let n=To(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let i=t.kind==="rename-type"?"type":"status";n[i]=xt(n[i],t)}function Ao(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let i=n;return t.kind==="rename-type"?Uw(i,t):t.kind==="rename-field"?zw(i,t):Hw(i,t),Ww(i,t),`${JSON.stringify(i,null,2)}
|
|
27
|
-
`}function wm(e,t){if(t.kind==="rename-type"){let i=tt(e).definitions;return{source:i.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:i.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let i=Kt(e).fields;return{source:i.some(r=>r.key===t.from),target:i.some(r=>r.key===t.to)}}let n=Xt(e).statuses;return{source:n.some(i=>i.id===t.from),target:n.some(i=>i.id===t.to)}}function qw(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Gw(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function vm(e,t){let n=Co(t.request),i=t.migrationId===void 0?_m(n,t.migrationScope??"plan"):hm(t.migrationId),r=e.map(c=>Gw(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),a=fm("sha256").update(JSON.stringify({migrationId:i,request:n,items:r})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=r.filter(c=>!o.has(c.id));return Object.freeze({migration_id:i,request:n,fingerprint:a,affected_item_count:r.length,pending_item_count:s.length,skipped_completed_count:r.length-s.length,items:Object.freeze(s)})}async function Bw(e){let t=H(e.settings,F()),n=[...new Set(Object.values(t.type_to_folder))],i=await mr(e.pmRoot,n),r=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},a=i?await nl({pmRoot:e.pmRoot,expectedSourceCursor:i.source_cursor,query:r}):null;return a?{items:a.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await it(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Jw(e,t){let n=await B(gm(e,t));if(n===null)return null;try{let i=JSON.parse(n);if(i.schema_version!==1||i.plan.migration_id!==t||!Array.isArray(i.plan.items))throw new TypeError("invalid plan envelope");return i.plan}catch(i){throw new g(`Stored schema migration plan "${t}" is invalid: ${Ac(i)}`,y.GENERIC_FAILURE)}}async function Vw(e,t){let n=gm(e,t.migration_id);await gn.mkdir(yn.dirname(n),{recursive:!0});let i={schema_version:1,plan:t,created_at:new Date().toISOString()};await Z(n,`${JSON.stringify(i,null,2)}
|
|
28
|
-
`)}function Kw(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Yw(e){let t=await ge(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new g(`Schema migration item "${e.id}" no longer exists.`,y.NOT_FOUND);return(await ye(t,{schema:e.settings.schema})).document.metadata}function mm(e,t,n){let i=n==="forward"?t.from:t.to,r=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==i.toLowerCase())throw new TypeError(`Schema migration expected type "${i}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==i.toLowerCase())throw new TypeError(`Schema migration expected status "${i}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let a=e.metadata;if(Object.prototype.hasOwnProperty.call(a,r)&&!Object.prototype.hasOwnProperty.call(a,i))return[];if(!Object.prototype.hasOwnProperty.call(a,i)||Object.prototype.hasOwnProperty.call(a,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return a[r]=a[i],delete a[i],[i,r]}function pm(e){return{id:e.id,inspect:async()=>{let t=await _n(e.filePath),n=wm(t.raw,e.request),i=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:i?"applied":"pending",...i?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await _n(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await _n(e.filePath);return await Z(e.filePath,Fw(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await ym(e.filePath,{exists:t.exists,raw:t.raw})}}}function Xw(e){return{id:e.stepId,inspect:async()=>{let t=await _n(e.filePath);return{state:Ao(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await _n(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await _n(e.filePath);return await Z(e.filePath,Ao(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await ym(e.filePath,{exists:t.exists,raw:t.raw})}}}function Zw(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=H(t,F()).type_to_folder,i=await Yw({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=qw(i,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=H(t,F()).type_to_folder,i=await at({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(r){return{changedFields:mm(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:i.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=H(t,F()).type_to_folder;await at({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(i){return{changedFields:mm(i,e.request,"reverse")}}})}}}async function Qw(e){let t=await Jw(e.pmRoot,e.migrationId);if(t){if(!Kw(t.request,e.request))throw new g(`Schema migration id "${e.migrationId}" already belongs to a different request.`,y.CONFLICT);return{plan:t,stored:!0}}let n=await Bw({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...vm(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function ev(e){let t=wm(await B(e.schemaPath)??"",e.request);if(!t.source)throw new g(`Schema migration source "${e.request.from}" is not a custom definition.`,y.NOT_FOUND);if(t.target)throw new g(`Schema migration target "${e.request.to}" already exists.`,y.CONFLICT);await Vw(e.pmRoot,e.plan)}async function tv(e){let t=Ie(e.settings.schema),n=[...new Set([["types",Te.types],["fields",Te.fields],["workflows",Te.workflows]].map(([r,a])=>Ve(e.pmRoot,t.files[r],a)).filter(r=>r!==e.schemaPath))];try{let r=yn.join(e.pmRoot,"templates"),a=await gn.readdir(r,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>yn.join(r,o.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||!j(r))throw r}n.sort((r,a)=>r.localeCompare(a));let i=[];for(let r of n){let a=await B(r);a!==null&&Ao(a,e.request)!==a&&i.push({filePath:r,beforeRaw:a})}return{paths:n,snapshots:i}}async function nv(e){for(let t of e.snapshots){let n=await gn.readFile(t.filePath,"utf8"),i=yn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Ga({pmRoot:e.pmRoot,author:e.author,documentPath:i,before:Dr(t.beforeRaw),after:Dr(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${i}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function iv(e,t,n){let i=Co(e),r=M(process.cwd(),n.path);await te(r);let a=t.migrationId===void 0?_m(i,await gn.realpath(r)):hm(t.migrationId),o=await T(r),s=z(t.author,o.author_default),c=await Qw({pmRoot:r,settings:o,migrationId:a,request:i}),d=c.plan;if(t.dryRun===!0)return{...d,action:i.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Lw(r,o,i),u=await B(l)??"";c.stored||await ev({pmRoot:r,schemaPath:l,request:i,plan:d});let m=await tv({pmRoot:r,schemaPath:l,settings:o,request:i}),f=[pm({id:"stage-schema",filePath:l,request:i,phase:"stage"}),...m.paths.map((w,v)=>Xw({filePath:w,request:i,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Zw({pmRoot:r,id:w.id,request:i,author:s,force:t.force===!0})),pm({id:"retire-source",filePath:l,request:i,phase:"retire"})],p=await um({pmRoot:r,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),h=await gn.readFile(l,"utf8"),{historyPath:_}=await Ga({pmRoot:r,author:s,documentPath:yn.relative(r,l).replaceAll("\\","/"),before:Dr(u),after:Dr(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${i.kind}: ${i.from} -> ${i.to}; affected=${d.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await nv({pmRoot:r,author:s,settings:o,request:i,plan:d,snapshots:m.snapshots}),{...d,action:i.kind,applied:!0,recovered:p.recovered,migrated_item_count:d.affected_item_count,workspace_history_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]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var LD=[...Fi,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Or="schema-types",bm="schema-statuses",km="schema-fields";function It(e){return rn({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function jD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{r=Ma({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new g(f instanceof Error?f.message:String(f),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=Ve(i,o.files.types,Te.types),c=[],d=z(t.author,a.author_default),l=Me(a),u=await re(i,Or,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms),m;try{let f=await B(s),p;try{p=tt(f)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.GENERIC_FAILURE)}try{Gc(r,p);let h=new Map,_=H(a,F());for(let[w,v]of Object.entries(_.type_to_folder)){let E=v.trim().toLowerCase();E.length>0&&!h.has(E)&&h.set(E,w)}Bc(r,p,h)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}m=zi(p,r),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await It({pmRoot:i,filePath:s,raw:yt(m.file),op:"schema:add-type",author:d,settings:a}),await oi(i,[m.definition],c,"schema:add-type-folder"),c.push(...await K({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await Em(i,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Rt(c),generated_at:$()}}async function dt(e){await te(e)}async function Em(e,t){try{let n=await Tl(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Rt(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function ov(e,t,n,i){let r=H(t,F()),a=i.trim().toLowerCase();return(await it(e,t.item_format,r.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function sv(e,t,n,i){let r=H(t,F()),a=fe(n),o=se(i);return(await it(e,t.item_format,r.type_to_folder,[],n)).filter(s=>{let c=typeof s.status=="string"?s.status:"";return(a.alias_to_id.get(se(c))??se(c))===o}).length}async function cv(e,t,n,i,r){if(r.length===0||Fa.has(r))return;let a=await sv(t,n,i,r);a>0&&e.push(`items_using_status:${a}`);let o=dv(i.workflow,r);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function dv(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&se(n)===t).map(([n])=>n)}async function FD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r=await T(i),a=Ie(r.schema),o=Ve(i,a.files.types,Te.types),s=[],c=z(t.author,r.author_default),d=Me(r),l=await re(i,Or,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await B(o),f;try{f=tt(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=Jc(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await ov(i,r,a,p);h>0&&s.push(`items_using_type:${h}`)}await It({pmRoot:i,filePath:o,raw:yt(u.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await K({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await Em(i,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:o,definitions:u.file.definitions.length},warnings:Rt(s),generated_at:$()}}function $o(e,t){return Ve(e,t.files.statuses,Te.statuses)}function Pr(e,t){return Ve(e,t.files.fields,Te.fields)}function Sm(e,t){return Ve(e,t.files.types,Te.types)}async function oi(e,t,n,i){for(let r of t){let a=Tc(r.folder??Cc(r.name)),o=rv.join(e,a);await D(o)||(await av(o,{recursive:!0}),n.push(...await K({path:o,scope:"project",op:i})))}}function Do(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function lv(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function uv(e){let t=new Map;for(let n of e){let i=se(n.id);if(i.length!==0){t.set(i,i);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let a=se(r);a.length>0&&!t.has(a)&&t.set(a,i)}}}return t}async function UD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{r=td({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=$o(i,o),c=fe(o);try{Ua(r,c.alias_to_id)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let d=lv(c.by_id.get(r.id));if((r.roles??d?.roles??[]).length===0)throw new g(`Status "${r.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,y.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Vt(r.id)}" --role active`,`pm schema add-status "${Vt(r.id)}" --role blocked`]});let l=[],u=z(t.author,a.author_default),m=Me(a),f=await re(i,bm,a.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),p;try{let h=await B(s),_;try{_=Xt(h)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=uv(_.statuses);try{Ua(r,w)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.USAGE)}p=nd(_,r,d),await It({pmRoot:i,filePath:s,raw:Zt(p.file),op:"schema:add-status",author:u,settings:a}),l.push(...await K({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:Rt(l),generated_at:$()}}async function HD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r=await T(i),a=Ie(r.schema),o=$o(i,a),s=[],c=z(t.author,r.author_default),d=Me(r),l=await re(i,bm,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await B(o),f;try{f=Xt(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=id(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=se(u.definition?.id??e);await cv(s,i,r,a,p),await It({pmRoot:i,filePath:o,raw:Zt(u.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await K({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:o,statuses:u.file.statuses.length},warnings:Rt(s),generated_at:$()}}function xm(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function mv(e,t,n){return{...xm(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function Im(e){return{id:e.id,source:Fa.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Rm(e,t,n){let i=e.toLowerCase();return n.has(i)?"extension":t.has(i)?"custom":"builtin"}function pv(){let e=new Map,t=F();for(let n of t?.item_types??[]){let i=n.types;if(Array.isArray(i))for(let r of i){if(typeof r!="object"||r===null||Array.isArray(r))continue;let a=r.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function fv(e){let t=fe(e),n=[],i=[];for(let r of t.definitions){let a=Im(r);a.source==="builtin"?n.push(a):i.push(a)}return{builtin:n,custom:i}}async function si(e){let t=M(process.cwd(),e.path);await dt(t);let n=await T(t),i=Ie(n.schema),r=Ve(t,i.files.types,Te.types),a=$o(t,i),o=H(n,F()),s=pv(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:r,statusesPath:a,byType:o.by_type,customNames:c,extensionProvenance:s,schema:i}}async function zD(e){let t=await si(e),n=[],i=[],r=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Rm(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=xm(s);c==="extension"?r.push(d):c==="custom"?i.push(d):n.push(d)}let a=fv(t.schema),o=Wi(t.schema).definitions.map(Do);return{action:"list",builtin:n,custom:i,extension:r,counts:{builtin:n.length,custom:i.length,extension:r.length,total:n.length+i.length+r.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:$()}}async function WD(e,t){let n=(e??"").trim();if(n.length===0)throw new g("Type name must not be empty.",y.USAGE);let i=await si(t),r=Object.values(i.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!r)throw new g(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Vt(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:mv(r,Rm(r.name,i.customNames,new Set(i.extensionProvenance.keys())),i.extensionProvenance.get(r.name.toLowerCase())),file:{path:i.typesPath},generated_at:$()}}async function qD(e,t){let n=se(e);if(n.length===0)throw new g("Status id must not be empty.",y.USAGE);let i=await si(t),r=fe(i.schema),a=r.alias_to_id.get(n)??n,o=r.by_id.get(a);if(!o)throw new g(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Vt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Im(o),file:{path:i.statusesPath},generated_at:$()}}async function GD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{r=Yc({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=Pr(i,o),c=[],d=Vi(r.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=z(t.author,a.author_default),u=Me(a),m=await re(i,km,a.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,a.locks.wait_ms),f;try{let p=await B(s),h;try{h=Kt(p)}catch(_){throw new g(_ instanceof Error?_.message:String(_),y.GENERIC_FAILURE)}f=Xc(h,r),await It({pmRoot:i,filePath:s,raw:Yt(f.file),op:"schema:add-field",author:l,settings:a}),c.push(...await K({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Rt(c),generated_at:$()}}async function hv(e,t,n,i){let r=H(t,F());return(await it(e,t.item_format,r.type_to_folder,[],n)).filter(a=>{let o=a[i];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function BD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r=await T(i),a=Ie(r.schema),o=Pr(i,a),s=[],c=z(t.author,r.author_default),d=Me(r),l=await re(i,km,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await B(o),f;try{f=Kt(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=Zc(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=se(u.definition?.key??e),h=se(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let _=await hv(i,r,a,h);_>0&&s.push(`items_using_field:${_}`)}await It({pmRoot:i,filePath:o,raw:Yt(u.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await K({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:o,fields:u.file.fields.length},warnings:Rt(s),generated_at:$()}}async function JD(e){let t=await si(e),n=Wi(t.schema).definitions.map(Do);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Pr(t.pmRoot,t.schema)},generated_at:$()}}async function VD(e,t){let n=se(e);if(n.length===0)throw new g("Field key must not be empty.",y.USAGE);let i=await si(t),r=Wi(i.schema).by_key.get(n);if(!r)throw new g(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Vt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Do(r),file:{path:Pr(i.pmRoot,i.schema)},generated_at:$()}}async function KD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{let h=Kc(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${Vc.join(", ")}.`);r=h}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=Sm(i,o),c=[],d=z(t.author,a.author_default),l=Me(a),u=[],m=[],f,p=await re(i,Or,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms);try{let h=await B(s),_;try{_=tt(h)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=_;for(let v of ja(r)){let E=zi(w,v);w=E.file,(E.replaced?m:u).push(E.definition.name)}f=w.definitions.length,await It({pmRoot:i,filePath:s,raw:yt(w),op:"schema:apply-preset",author:d,settings:a}),await oi(i,ja(r),c,"schema:apply-preset-folder"),c.push(...await K({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:r,registered:u,replaced:m,file:{path:s,definitions:f},warnings:Rt(c),generated_at:$()}}function _v(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new g("--min-count must be a positive integer (>= 1).",y.USAGE);return e}async function YD(e,t){let n=M(process.cwd(),t.path);await dt(n);let i=await T(n),r=Ie(i.schema),a=Sm(n,r),o=_v(e.minCount),s=H(i,F()),c=(await it(n,i.item_format,s.type_to_folder,[],r)).map(v=>typeof v.title=="string"?v.title:""),d=im(c,{minCount:o}),l=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=tt(await B(a))}catch(E){throw new g(E instanceof Error?E.message:String(E),y.GENERIC_FAILURE)}return p=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:l,generated_at:$()}}let h=z(e.author,i.author_default),_=Me(i),w=await re(n,Or,i.locks.ttl_seconds,h,!!e.force,_.force_required_for_stale_lock,i.locks.wait_ms);try{let v=await B(a),E;try{E=tt(v)}catch(I){throw new g(I instanceof Error?I.message:String(I),y.GENERIC_FAILURE)}let k=E;for(let I of d){if(I.shadows_builtin){f.push({name:I.name,reason:"shadows_builtin"});continue}let C;try{C=Ma({name:I.name})}catch{f.push({name:I.name,reason:"invalid_type_token"});continue}let S=zi(k,C);k=S.file,(S.replaced?m:u).push(S.definition.name)}p=k.definitions.length,await It({pmRoot:n,filePath:a,raw:yt(k),op:"schema:infer-types",author:h,settings:i}),await oi(n,k.definitions.filter(I=>u.includes(I.name)||m.includes(I.name)),l,"schema:infer-types-folder"),l.push(...await K({path:a,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:Rt(l),generated_at:$()}}import Am from"node:fs/promises";import Oo 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]="9cf5a9e7-4a66-5e72-80a2-f8a9b5b6e412")}catch{}})();function Ce(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function R(e){return e.trim().toLowerCase()}function Lr(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let i=t.length;for(;i>n&&t[i-1]==="-";)i-=1;let r=t.slice(n,i);if(r.length===0)throw new g("Extension manifest name must resolve to a non-empty directory name.",y.USAGE);if(r==="."||r==="..")throw new g('Extension manifest name must not resolve to "." or "..".',y.USAGE);return r}function Po(e){return zc(e)}async function gv(e){try{let t=JSON.parse(await Am.readFile(Oo.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(i=>typeof t.scripts?.[i]=="string")}}catch{return{has_build_script:!1}}}async function yv(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new g(`Extension entry file is missing at "${t}".`,y.USAGE);let i=await gv(n.source_root),r=i.package_name?`pm package install npm:${i.package_name}`:void 0,a=n.source_input??n.source_root;return new g(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm package install copies GitHub repositories without running package scripts${i.has_build_script?", and this package declares a build or publish script":""}. ${r?`Try "${r}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,y.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:r?[r,`pm package install ${n.source_root}`]:[`pm package install ${n.source_root}`],nextSteps:r?[`Retry with ${r}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm package install npm:<package-name>."],recovery:{attempted_command:`pm install ${a}`,normalized_args:["install",a],...r?{next_best_command:r}:{}}})}async function vn(e,t={}){let n=Oo.join(e,"manifest.json");if(!await D(n))throw new g(`Extension manifest is missing at "${n}".`,y.USAGE);let i;try{i=JSON.parse(await Am.readFile(n,"utf8"))}catch(o){throw new g(`Failed to parse extension manifest at "${n}": ${wv(o)}`,y.USAGE)}let r=Po(i);if(!r)throw new g(`Extension manifest at "${n}" is invalid.`,y.USAGE);let a=Oo.resolve(e,r.entry);if(!me(e,a))throw new g(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await D(a))throw await yv(r,a,t);if(!await Wc(e,a))throw new g(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,y.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:r}}function wv(e){return e instanceof Error?e.message:String(e)}import Lo from"node:fs/promises";import vv 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]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var bv=".managed-extensions.json",Nr=1;function ci(e){return vv.join(e,bv)}function kv(){return{version:Nr,updated_at:$(),entries:[]}}function di(e){return[...e].sort((t,n)=>{let i=t.scope.localeCompare(n.scope);if(i!==0)return i;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Cm(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function ve(e){return typeof e=="string"?e:void 0}function Ev(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Sv(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:ve(t.name),package:ve(t.package),version:ve(t.version),repository:ve(t.repository),owner:ve(t.owner),repo:ve(t.repo),ref:ve(t.ref),subpath:ve(t.subpath),commit:ve(t.commit)}}function xv(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Ev(t))return null;let n=Sv(t.source);if(!n)return null;let i=Uc(t.contributions);return i===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Ce(t.capabilities),contributions:i,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ve(t.last_update_check_at),last_update_remote_commit:ve(t.last_update_remote_commit),last_update_remote_version:ve(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ve(t.update_error)}}function Iv(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Nr||!Array.isArray(t.entries))return null;let n=[];for(let i of t.entries){let r=xv(i);r&&n.push(r)}return{version:Nr,updated_at:ve(t.updated_at)??$(),entries:di(n)}}async function he(e){let t=ci(e),n=kv();try{let i=await Lo.readFile(t,"utf8"),r=JSON.parse(i),a=Iv(r);if(!a)throw new g(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(i){if(i instanceof g)throw i;if(typeof i=="object"&&i!==null&&"code"in i&&j(i))return{path:t,state:n,warnings:[]};throw new g(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE)}}async function bn(e,t){let n=ci(e),i={version:Nr,updated_at:$(),entries:di(t.entries)};await Lo.mkdir(e,{recursive:!0}),await Lo.writeFile(n,`${JSON.stringify(i,null,2)}
|
|
29
|
-
`,
|
|
30
|
-
${
|
|
31
|
-
|
|
32
|
-
`,"utf8");try{await Promise.all([J.rm(N.join(e,"package-lock.json"),{force:!0}),J.rm(N.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await cb(e)}finally{await J.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
33
|
-
`,"utf8")}}function ob(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Fr in t)return!0;return!1}function sb(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let i={...n};delete i[Fr],Object.keys(i).length===0?delete e[t]:e[t]=i}}async function cb(e){let t=qe(import.meta.url,["../../.."]),[n,i]=Fr.split("/"),r=N.join(e,"node_modules",n),a=N.join(r,i);await J.mkdir(r,{recursive:!0}),await J.rm(a,{recursive:!0,force:!0}),await J.symlink(t,a,db(process.platform))}function db(e){return e==="win32"?"junction":"dir"}function lb(e,t){if(e.startsWith("-"))throw new g(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,y.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let i=n.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(n)}))throw new g(`Extension runtime dependency "${e}" has an unsafe version specifier.`,y.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Uv.resolve(e,t)}catch{throw new g(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,y.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function ub(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[i,r]of Object.entries(n)){if(i===Fr||typeof r!="string"||r.trim().length===0||t.has(i))continue;let a=r.trim();t.set(i,lb(i,a))}return[...t.values()]}async function Ur(e,t){let n=await Hi(e);if(n.length===1)return n[0];if(n.length>1){let i=n.map(r=>N.relative(e,r).replaceAll(N.sep,"/")).sort((r,a)=>r.localeCompare(a));throw new g(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${i.join(", ")}`,y.USAGE)}throw new g(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,y.USAGE)}async function mb(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(N.posix.join(".agents/pm/extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extension",t.subpath)));for(let r of n){let a=N.resolve(e,r);if(me(e,a)&&await D(N.join(a,"manifest.json")))return{directory:a,resolved_subpath:r}}if(await D(N.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let i=await Ur(e,t.input);return{directory:i,resolved_subpath:N.relative(e,i).replaceAll(N.sep,"/")}}function pb(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function fb(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!pb(n))return new g(t,y.NOT_FOUND);let i=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?N.resolve(a.trim()):"";jo?.key!==o&&(jo={key:o,aliases:await Mr()}),i=jo.aliases}catch{}let r=[`Retry with pm package install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${i.join(", ")}`];return new g(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,y.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm package install npm:${n}`,"pm package catalog --project --json"],nextSteps:r,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function Gm(e){if(e.kind==="local"){let i;try{i=await J.stat(e.absolute_path)}catch{throw await fb(e)}if(i.isFile()&&qm(e.absolute_path)){let a=await Uo(e.absolute_path);return{source:e,directory:a.directory,source_root:N.dirname(a.directory),resolved_subpath:N.relative(N.dirname(a.directory),a.directory).replaceAll(N.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!i.isDirectory())throw new g(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,y.USAGE);let r=await Ur(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let i=await nb(e);return{source:e,directory:i.directory,source_root:N.dirname(i.directory),cleanup:i.cleanup,resolved_subpath:N.relative(N.dirname(i.directory),i.directory).replaceAll(N.sep,"/"),npm_package:i.package,npm_version:i.version}}let t=await J.mkdtemp(N.join(Ho.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await jr(n);let i=await jr(["-C",t,"rev-parse","HEAD"]),r=await mb(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:i,cleanup:async()=>{await J.rm(t,{recursive:!0,force:!0})}}}catch(i){throw await J.rm(t,{recursive:!0,force:!0}),i}}async function kn(e,t){if(!await D(e)||!await D(t))return!1;let[n,i]=await Promise.all([J.realpath(e),J.realpath(t)]);return n===i}import pi from"node:fs/promises";import fi 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]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var qo=1,zt="2026.6.24",hb=">=22.18.0",_b={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Bm=new Set([...Fc.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(jc).map(e=>e.toLowerCase()),"scaffold"]),gb="^6.0.0",yb="^22.0.0",Km=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],Xe=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Jm(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function Ym(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Xm(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var wb={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Vm=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Zm={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},vb={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},bb={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},kb={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},Qm="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Eb={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},Sb={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},xb={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},Ib={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function ep(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function tp(e,t){return e==="schema"?xb[t]:e==="profile"?Ib[t]:Sb[t]}function Rb(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),i=0;for(;t[i]?.toLowerCase()==="starter";)i+=1;let r=t[i]?.toLowerCase(),a=i>0&&(i===t.length||r!==void 0&&Bm.has(r));return`${(Bm.has(n)||a?["starter",...t]:t).join(" ")} ping`}function np(e){let t=e,n=`${e}s`,i=e.replace(/-/g,""),r=i===t?[]:[i],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Ab(e,t,n){let i=`${e}-search`,r=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(i)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...np(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Cb(e,t,n){let i=n==="hooks",r=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=vb[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,_=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=i?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});",""]:[],E=r?Go(e,t,"search",m):[],k=a?Go(e,t,"importers",m):[],I=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Jm(Ym({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});",""]:[],C=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Jm(Xm(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});",""]:[],S=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});",""]:[],b=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});",""]:[],O=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});",""]:[],P=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Km,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});","",...v,...E,...k,...I,...C,...S,...b,...O,...P,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
34
|
-
`)}function Tb(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let i=`${e.replace(/-/g," ")} items`;return[t,`${i} import`,`${i} export`]}return[t]}var $b={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},Db={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function Ob(e,t,n){let i=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...i?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...i?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Pb(e,t,n){let i=[],r=[...Ob(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":i.push("defineAfterCommandHook"),r.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":i.push("defineSearchProvider","defineVectorStoreAdapter"),r.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":i.push("defineExporter","defineImporter"),r.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":i.push("defineItemField","defineItemType","defineMigration"),r.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":i.push("defineProjectProfile"),r.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...np(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":i.push("defineRendererOverride"),r.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":i.push("defineParserOverride"),r.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":i.push("definePreflightOverride"),r.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),a.push(" preflights: [preflightOverride],");break;case"services":i.push("defineServiceOverride"),r.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:i,definitions:r,blueprintFields:a}}function Lb(e,t,n){let i=Pb(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...i.builderImports].sort((r,a)=>r.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...i.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...i.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
35
|
-
`)}function Go(e,t,n,i){if(n==="commands")return[];let r=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(Ym({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Xm(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function Nb(e,t,n){let i=n==="parser",r=JSON.stringify([...Zm[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...Km,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(zt)},`," },",` target: { pmVersion: ${JSON.stringify(zt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${r});`,` assert.deepEqual(report.manifest?.capabilities, ${r});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...i?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Xe,"});","",...Go(e,t,n,r)].join(`
|
|
36
|
-
`)}function
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
`,
|
|
41
|
-
|
|
42
|
-
`),w=jb(e),v=["```ts",`import { ${Fb(i)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Ub(e,t,i,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Hb(t,i,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],E=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,Qm,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Eb[i],...tp(i,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${zt}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${qo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${zt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
43
|
-
`);return{"package.json":f,"manifest.json":c,"index.ts":r?Lb(e,t,i):d,"index.test.ts":r?Nb(e,t,i):p,"tsconfig.json":l,".gitignore":_,"README.md":r?Mb(a,t,i):E}}async function ip(e,t="extension",n="commands",i=!1){let r=n.trim().toLowerCase();if(!Vm.includes(r))throw new g(`Unknown scaffold capability "${n}". Supported capabilities: ${Vm.join(", ")}.`,y.USAGE);let a=r;if(i&&t!=="package")throw new g("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",y.USAGE);let o=i?"declarative":"imperative",s=e.trim(),c=fi.resolve(process.cwd(),s),d=Lr(fi.basename(c)).replace(/^(?:pm-)+/u,""),l=Rb(d),u=zb(d,l,t,a,i),m=!1;if(await D(c)){if(!(await pi.stat(c)).isDirectory())throw new g(`Scaffold target "${c}" exists and is not a directory.`,y.CONFLICT)}else await pi.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let _=fi.join(c,p);if(await D(_)&&await pi.readFile(_,"utf8")!==h)throw new g(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,y.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let _=fi.join(c,p);if(await D(_)){f.push({path:p,status:"unchanged"});continue}await pi.mkdir(fi.dirname(_),{recursive:!0}),await pi.writeFile(_,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:a,style:o,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function rp(e,t){return`${e}:${R(t)}`}function Wb(e,t){let n=[];for(let[i,r]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of r){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(d=>t.has(R(d.name))))continue;let c=s.at(-1);n.push({command:o,surface:i,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((i,r)=>i.command.localeCompare(r.command)||i.surface.localeCompare(r.surface))}function ap(e,t,n){let i=new Set(n.failed.map(d=>rp(d.layer,d.name))),r=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:i.has(rp(d.layer,d.name))?"failed":"ok",surfaces:hn(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:hn(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),a=typeof e=="string"?R(e):null,o=a===null?null:new Set(t.loaded.filter(d=>R(d.name)===a||typeof d.source_package=="string"&&R(d.source_package)===a||(d.source_aliases??[]).some(l=>R(l)===a)).map(d=>R(d.name)).concat(a)),s=o===null?r:r.filter(d=>o.has(R(d.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:hn(n,c),command_ownership:Wb(n,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]="573b0fd6-f003-55d8-8f49-c2a5e81cbc31")}catch{}})();function Bo(e){return e.map(({layer:t,name:n,error:i})=>({layer:t,name:n,error:i}))}function Hr(e,t,n){let i=R(t),r=n.trim();if(i.length===0||r.length===0)return;let a=e.get(i)??new Set;a.add(r),e.set(i,a)}function qb(e){let t=new Map,n=new Map;for(let i of e.registrations.commands)Hr(t,i.name,i.command),Hr(n,i.name,i.action);for(let i of e.commands.handlers)Hr(t,i.name,i.command);for(let i of e.commands.overrides)Hr(t,i.name,i.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function op(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Gb(e){let{enabled:t,normalizedName:n,loadedNames:i,loadFailedNames:r,activationFailedNames:a}=e;return t?r.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:i.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function zr(e,t,n){let i=new Set(t.loaded.map(c=>R(c.name))),r=new Set(t.failed.map(c=>R(c.name))),a=new Set(n.failed.map(c=>R(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=qb(n);return e.map(c=>{let d=R(c.name),l=op(o.get(d)),u=op(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=Gb({enabled:c.enabled,normalizedName:d,loadedNames:i,loadFailedNames:r,activationFailedNames:a});return{...c,...f,...m}})}function Bb(e){let t=0,n=0,i=0;for(let r of e)if(r.startsWith("extension_policy_")){if(t+=1,r.startsWith("extension_policy_violation_")){n+=1;continue}r.startsWith("extension_policy_blocked_")&&(i+=1)}return{warning_count:t,violation_count:n,blocked_count:i}}function de(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var dp=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function Jb(e){return dp.has(hp(e))}function sp(e){return e==="project"||e==="global"}function lp(e){let t=e.split(":"),n=t[0];if(!n||!dp.has(n))return null;let i=t.at(-4),r=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!sp(i)||!sp(a)||!r||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:i,name:r},displaced:{layer:a,name:o}}}function Vb(e){let t=new Set;for(let n of e){let i=lp(n);i&&(t.add(i.winner.name),t.add(i.displaced.name))}return[...t].sort((n,i)=>n.localeCompare(i))}function Jo(e,t){let n=e.filter(Jb);if(n.length===0)return null;let i=Vb(n);return`Extension registration collisions or handler/override overlaps detected.${i.length>0?` Conflicting extensions: ${i.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function Kb(e,t,n,i){let r=t.map(u=>lp(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(r.length===0)return;let a=e==="global"?"--global":"--project",o=de(i,"deactivate"),s=`${de(i,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[R(u.name),u])),d=new Map;for(let u of r)for(let m of[u.winner.name,u.displaced.name]){let f=R(m);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],_=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${o} ${p} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[..._].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:d.size,next_best_command:s,collisions:r,remediation_candidates:l}}function up(e){let t=[];for(let n of e){let i=n.error.toLowerCase();(i.includes("cannot find package '@unbrained/pm-cli'")||i.includes('cannot find module "@unbrained/pm-cli"')||i.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(i.includes("cannot use import statement outside a module")||i.includes("to load an es module")||i.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}function mp(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let i of t){if(!i||typeof i.name!="string")continue;let r=i.trace?.missing_capability??i.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${i.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function pp(e,t){let n=[];for(let i of od(e.loaded,t))for(let r of i.unused)n.push(`extension_capability_unused:${i.layer}:${i.name}:${r}`);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}var Yb=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${de(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Li.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${de(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${de(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${de(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function Xb(e){let{normalizedWarnings:t,options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=t.map(ri).filter(f=>f!==void 0),m={options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let f=Jo(t,{deactivate:`${de(n,"deactivate")} <name> ${r}`,doctor:`${de(n,"doctor")} ${r} --detail deep --trace`});f&&u.push(f);for(let p of Yb)p.matches(t,m)&&u.push(p.build(m))}return s>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${de(n,"manage")} ${r} --fix-managed-state (or ${de(n,"adopt-all")} ${r}, ${de(n,"adopt")} <name> ${r}, or reinstall via ${de(n,"install")} ${r} <source>).`),d>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${de(n,"manage")} ${r} to request update checks.`),l>0&&u.push(`Update available managed extensions via ${de(n,"install")} ${r} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${de(n,"manage")} ${r} after extension changes.`),u}function Wr(e,t,n,i={}){let r=[...new Set(t)].sort((b,O)=>b.localeCompare(O)),a=n.filter(b=>b.managed).length,o=n.filter(b=>b.enabled).length,s=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,d=n.filter(b=>b.managed===!1),l=d.filter(b=>cp(b)).map(b=>b.name).sort((b,O)=>b.localeCompare(O)),u=d.filter(b=>!cp(b)).map(b=>b.name).sort((b,O)=>b.localeCompare(O)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let f=m.failed,p=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,O])=>`extension_update_health_partial_coverage:${b}:${O}`),_=h.length>0,w=_?"partial":"full",v=[...new Set([...r,...h])].sort((b,O)=>b.localeCompare(O)),E=[...new Set(v.map(b=>hp(b)))].sort((b,O)=>b.localeCompare(O)),k=Bb(v),I=e==="global"?"--global":"--project",C=Kb(e,r,n,i),S=Xb({normalizedWarnings:v,options:i,scope:e,scopeFlag:I,updateCheckFailedTotal:f,policyWarningCount:k.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:E,warnings:v,policy_warning_count:k.warning_count,policy_violation_count:k.violation_count,policy_blocked_count:k.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:_,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(b=>b.name).sort((b,O)=>b.localeCompare(O)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:S,...C?{collision_plan:C}:{}}}function fp(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new g(`Invalid --detail value "${e}". Expected summary or deep.`,y.USAGE)}function hp(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function hi(e){let t=new Set,n=[];for(let i of e){let r=(()=>{let a=yc(i);return a?[a]:wc(i)})();for(let a of r){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function _i(){return{version:Ni.version,capabilities:[...Ni.capabilities],legacy_aliases:{...Ni.legacy_aliases}}}function cp(e){let t=R(e.name),n=R(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function _p(e,t,n,i,r){if(e!=="project"||r)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(d=>d.active).map(d=>R(d.name)))].sort((d,l)=>d.localeCompare(l)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>R(d.name)))].sort((d,l)=>d.localeCompare(l)),s=new Set(i.map(d=>R(d.name))),c=a.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,l)=>d.localeCompare(l));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import gp 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]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function gi(e,t,n,i){let r=gp.relative(e,n);if(r!==""&&!me(e,n)||n===t||me(t,n))return!1;let a=r.split(gp.sep);return a.includes(".git")?!1:i?!a.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as Zb}from"node:crypto";import ne from"node:fs/promises";import Qb from"node:os";import X from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var yp=3,ek=120,wp=250,tk=12e4,nk=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),vp=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,bp=e=>nk.has(String(vp(e))),qr=(e,t)=>vp(e)===t,kp=e=>new Promise(t=>{setTimeout(t,e)}),Ep=async e=>{let t=X.join(e,"package.json");await D(t)||await ne.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
44
|
-
`,"utf8")},
|
|
45
|
-
`,"utf8")}catch(n){throw await ne.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},ok=async(e,t,n,i,r)=>{for(let a=1;a<=n;a+=1)try{return await ak(e,t),!0}catch(o){if(!qr(o,"EEXIST"))throw o;await ik(e,r)?a-=1:await kp(i)}return!1},Ko=async(e,t,n,i)=>Pt("extension_install",async()=>{let r=X.join(e,"runtime","extension-install-locks"),a=X.join(r,"scope.lock");await ne.mkdir(r,{recursive:!0});let{attempts:o=ek,delay_ms:s=wp,stale_ms:c=tk,heartbeat_ms:d}=i??{};if(![o,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new g("Extension install lock timings must be finite numbers.",y.USAGE);let l=Math.max(1,Math.floor(o)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(d??m/3);if(m<=0||f<=0||f>=m)throw new g("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",y.USAGE);let p={pid:process.pid,token:Zb(),created_at:$(),destination:t};if(!await ok(a,p,l,u,m))throw new g(`Timed out waiting for extension install lock for "${t}".`,y.CONFLICT);let h=rk(a,p.token,f),_=!1;try{let w=await n();return _=!0,w}finally{await h(),await Rp(a,p.token).catch(w=>{if(_)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var Yo=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o])}});return await Promise.all(a),i};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function Ap(e,t){let n=R(e),i=t.find(r=>R(r.name)===n);return{command_paths:[...i?.command_paths??[]].sort((r,a)=>r.localeCompare(a)),action_paths:[...i?.action_paths??[]].sort((r,a)=>r.localeCompare(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]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function Cp(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${R(a.name)}`]:[])),i=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>a.passThrough!==!0).filter(a=>!n.has(`${a.layer}:${R(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),r=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...i,...r])].sort((a,o)=>a.localeCompare(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]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Tp=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Vi(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,i)=>i.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as sk}from"node:child_process";import{promisify as ck}from"node:util";import dk from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var lk=ck(sk),Dp=1e4;function $p(e,t,n){if(typeof t=="string")try{let i=dk.resolve(e,t);if(i.type==="version")return i.fetchSpec}catch{}throw new Error(n)}async function uk(e,t){try{return(await lk(zo(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:Wo(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function Op(e,t=uk){let n=$();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let i=$p(e.package,e.version,"missing_or_invalid_installed_npm_version"),r=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Dp),a;try{a=JSON.parse(r)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(a)&&a.length===1?a[0]:a,s=$p(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==i,remote_version:s}}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(i)}}}var mk=(e,t,n)=>{let i=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),r=i.find(o=>o.ref.endsWith("^{}"))??i[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:r.commit,available:r.commit!==a}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},Xo=async(e,t=jr)=>{let n=$();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let i=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,i,`${i}^{}`],void 0,Dp);return mk(r,e.commit,n)}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(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]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var pk=4;async function Pp(e,t=!1){let n=await Yo(e.entries,pk,async i=>{if(!["github","npm"].includes(i.source.kind))return i;if(t)return{...i,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let r=i.source.kind==="github"?await Xo(i.source):await Op(i.source);return{...i,last_update_check_at:r.checked_at,last_update_remote_commit:"remote_commit"in r?r.remote_commit:void 0,last_update_remote_version:"remote_version"in r?r.remote_version:void 0,update_available:r.available,update_error:r.error}});return{...e,entries:di(n)}}import fk from"node:fs/promises";import hk 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]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function Zo(e){return hk.join(e,"extension-migrations.json")}function Lp(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Np(e,t){return`${e.layer}:${e.name}:${t}`}async function _k(e){let t=Zo(e);if(!await D(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await fk.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(i=>typeof i?.key=="string"&&(i.status==="applied"||i.status==="failed")):[]}}async function Qo(e,t){let n=await _k(e),i=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,a)=>{let o=Lp(r,a),s=i.get(Np(r,o));s&&(r.definition.status=s.status,s.status==="failed"?r.definition.reason=s.error:(delete r.definition.reason,delete r.definition.error,delete r.definition.message))}),n}async function gk(e){let t=await Qo(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),i=[],r=!1,a=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of a){let m=Lp(l,u),f=Np(l,m),p=n.get(f),h=String(l.definition.status??"pending").toLowerCase(),_=p?.status??(h==="applied"||h==="failed"?h:"pending");if(_==="applied"){i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"skipped"});continue}if(e.dryRun===!0){i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:_}));let E={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,E),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"applied"}),r=!0}catch(E){let k=E instanceof Error?E.message:String(E),I={key:f,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:k};n.set(f,I),l.definition.status="failed",l.definition.reason=k,i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"failed",error:k}),r=!0}}if(r){let l=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await rn({pmRoot:e.pmRoot,filePath:Zo(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
|
|
46
|
-
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let o=i.filter(l=>l.outcome==="pending").length,s=i.filter(l=>l.outcome==="applied").length,c=i.filter(l=>l.outcome==="skipped").length,d=i.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:Zo(e.pmRoot),total:i.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:d,migrations:i}}async function Mp(e){let t=await T(e.resolvedRoots.settings_root),n=await Be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Je(n);e.warnings.push(...n.warnings,...i.warnings);let r=await gk({pmRoot:e.resolvedRoots.pm_root,migrations:i.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:r,load_failure_count:n.failed.length,activation_failure_count:i.failed.length},r.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17cca82e-e9f9-5633-8d91-bc6c2b560d5f")}catch{}})();function jp(e,t){let n=e.filter(i=>i.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:i,result:r})=>{let a=r.details;return{alias:i,ok:r.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,previous_state_preserved:a.previous_state_preserved,rollback:a.rollback,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:r.warnings}})}}import Br from"node:fs/promises";import Gr 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]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var yk=new Set(["node_modules",".git","dist","build","coverage"]);async function Fp(e,t,n,i){let r=e.source.kind==="local"?await Br.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?r.isDirectory()?"directory":"archive":e.source.kind,o=await wk(e.directory,t,i),s={source_mode:a,...a==="archive"?{archive_bytes:r.size}:{},copy:o},c=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await D(Gr.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let d=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new g(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,y.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function wk(e,t,n={}){let{maxEntries:i=1e4,maxDepth:r=64,signal:a}=n;if(![i,r].every(u=>Number.isSafeInteger(u)&&u>0))throw new g("maxEntries and maxDepth must be positive safe integers.",y.USAGE);a?.throwIfAborted();let o=await Br.realpath(e),s=await yi(t),c=await kn(o,s);a?.throwIfAborted();let d=c?"in_place":me(o,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:i,max_depth:r};return d==="in_place"||await Up(o,0,l,a),l}async function Up(e,t,n,i){i?.throwIfAborted();let r=await Br.opendir(e);for await(let a of r){if(i?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=Gr.join(e,a.name);if(!gi(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(Gr.relative(n.source_directory,o).split(Gr.sep).some(s=>yk.has(s))&&(n.development_entries+=1),await vk(o,t,n,i),!n.complete)return}}async function vk(e,t,n,i){let r=await Br.lstat(e);if(i?.throwIfAborted(),r.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Up(e,t+1,n,i)}else r.isFile()?(n.files+=1,n.bytes+=r.size):r.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import bk from"node:fs/promises";import kk 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]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function Ek(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Sk(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function es(e){let t=kk.join(e,"manifest.json"),n;try{n=await bk.readFile(t,"utf8")}catch(s){if(gt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let i;try{i=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof i!="object"||i===null||Array.isArray(i))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let r=i,a=xc(r),o=Ek(r);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>Sk(o,s)),remediation:a.findings.map(s=>s.message)}}function Hp(e){return es(Ge(e))}import xk from"node:fs/promises";import Ik from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function Rk(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await xk.lstat(e.absolute_path),e}catch(a){if(!j(a))throw a}let n=e.input.trim(),i=t.filter(a=>a.source.kind==="npm"),r=(i.find(a=>a.name===n)??i.find(a=>a.directory===n)??i.find(a=>a.source.package===n))?.source.package;if(r===void 0)return e;try{let a=Ik(r);if(!a.registry||a.name!==r)return e}catch{return e}return mi(`npm:${r}`,{})}async function zp(e,t,n,i=[]){let r=typeof t=="string"?null:await ui(e),a=r===null?null:e.trim().toLowerCase(),o=a===null?null:await Pm(a),s=await Rk(mi(r??e,{forceGithub:typeof t=="string",ref:n}),i),c=a===null?null:await Fm(e);return{bundledAliasName:a,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:a===null?s.kind:"builtin",input:a??s.input,...o===null?{}:{package:o}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...a===null?[]:[{kind:"builtin",input:a,...o===null?{}:{package:o},command:`pm install ${a}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import Ue from"node:fs/promises";import En 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]="7c06c702-29ea-5552-aadc-52dfc9c238ef")}catch{}})();var ts=async e=>Ue.readFile(e).catch(t=>{if(qr(t,"ENOENT"))return null;throw t}),Ak=async(e,t,n,i,r)=>Pt("extension_install_backup",async()=>{let a=ci(e),o=Bt(t),[s,c]=await Promise.all([ts(a),ts(o)]);return i&&await Ue.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:i,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}}),Wp=async e=>Pt("extension_install_rollback",async()=>{await Ue.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Ue.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await Ue.rm(t,{force:!0});else if(t===e.settingsPath){let i=En.dirname(e.settingsPath),r=await T(i);try{await rn({pmRoot:i,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:z(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms})}finally{Jd(i)}}else await Ue.mkdir(En.dirname(t),{recursive:!0}),await Ue.writeFile(t,n)});async function qp(e,t){let n=await D(e.destinationDirectory),i=await kn(e.sourceDirectory,e.destinationDirectory);await Ue.mkdir(e.selectedRoot,{recursive:!0});let r=En.join(En.dirname(e.selectedRoot),"runtime","extension-installs");await Ue.mkdir(r,{recursive:!0});let a=await Ue.mkdtemp(En.join(r,".pm-extension-install-backup-")),o=En.join(a,"destination"),s=["package","install",o,`--${e.scope}`],c=le(s),d=!1;try{let l=await Ak(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,o),u;try{u=await t()}catch(m){try{await Wp(l)}catch(f){d=!0;let p=new g(`Extension install failed: ${String(m)}; rollback failed: ${String(f)}`,y.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:m instanceof g?m.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?c:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:c,suggested_retry_args:s}}:{}});throw Object.defineProperty(p,"cause",{value:m,configurable:!0,writable:!0}),p}throw m}if(u.ok)return u;if(!n||i)return{...u,details:{...u.details,previous_state_preserved:!1}};try{await Wp(l)}catch(m){return d=!0,{...u,details:{...u.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(m),backup_directory:o,recovery_command:c,recovery_args:s}}}}return{...u,details:{...u.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{d||await Ue.rm(a,{recursive:!0,force:!0}).catch(()=>{})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ae11424-9de8-5bce-91b4-e8901459fb5f")}catch{}})();var Vp=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Ck=Vp.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Tk={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},$k="__pm_native_output",Dk=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Kp=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Ok=["disabled","require_trusted","require_provenance"],Yp={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Pk=e=>{let t=e??Yp,n={};for(let i of Dk)n[i]=Ce(t[i]??[]);return n},Lk=(e,t)=>{for(let n of Kp)t[n].length>0&&(e[n]=t[n]);return e},Nk=(e,t)=>{for(let n of Ok)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Mk=e=>{let t={};for(let n of Kp)t[n]=Ce(e[n]??[]);return t},jk=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Lk(Nk({name:t},e),Mk(e))},Fk=e=>(e??[]).map(t=>jk(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Uk=e=>{let t=Object.assign({},Yp,e??{}),n=Pk(e),i=Fk(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:i}},Xp=async(e,t)=>{let n=[t],i=await Lm(t);i&&n.push(i);let r=[...new Set(n.map(a=>R(a)).filter(a=>a.length>0))];for(let a of r){let o=e.find(c=>R(c.name)===a);if(o)return o;let s=e.find(c=>R(c.directory)===a);if(s)return s}},Zp=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled));return new Set(Ce(e.extensions.disabled)).has(n)?!1:i.size===0?!0:i.has(n)},Qp=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled)),r=new Set(Ce(e.extensions.disabled)),a=[...i],o=[...r];return r.delete(n),i.size>0&&i.add(n),e.extensions.enabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Hk=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled)),r=new Set(Ce(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.add(n),e.extensions.enabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},zk=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled)),r=new Set(Ce(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.delete(n),e.extensions.enabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Wk=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),i=Vp.map(([r,a,o])=>({action:a,flag:o,distance:gc(t,r,n)})).filter(r=>r.distance!==null).sort((r,a)=>r.distance-a.distance)[0];return i?{action:i.action,flag:i.flag}:null},qk=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=Wk(e);if(!i)return new g(`One action flag is required. Use one of: ${Ck}. Bare \`pm package\` and \`pm extension\` default to --explore.`,y.USAGE);let r=`pm ${n} ${i.flag}`;return Yi({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(ef),retry_command:r,message_suffix:`. Did you mean "${i.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},Gk=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],ef={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Bk=e=>ef[e]??null,Jk=(e,t)=>{let n=[...new Set(Gk.filter(([i])=>t[i]===!0).map(([,i])=>i))];if(n.length===0){if(e===void 0)return"explore";let i=Bk(e.trim().toLowerCase());if(i)return i;throw qk(e,t)}if(n.length>1)throw new g("Extension action flags are mutually exclusive.",y.USAGE);return n[0]},Vk=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new g('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"},Kk=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],tf=e=>{for(let t of Kk){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},nf=(e,t,n,i)=>{let r=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:r.contributions,managed:!!n,source:r.source,update_available:r.update_available,last_update_check_at:r.last_update_check_at,last_update_remote_commit:r.last_update_remote_commit,last_update_remote_version:r.last_update_remote_version,update_error:r.update_error,update_check_status:i.status,update_check_reason:i.reason}},Yk=(e,t,n,i)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},i),a=i?Zp(n,i.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:nf({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:a},t,i,tf(i))}},Xk=async(e,t,n,i,r,a)=>{let o=Oe.join(e,t),s=Oe.join(o,"manifest.json"),c=a.get(R(t));if(!await D(s))return Yk(t,n,i,c);let d=Symbol("invalid-extension-manifest-json"),l=await Sn.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Po(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=r.get(R(u.name))??a.get(R(t));return{summary:nf({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Zp(i,u.name)},n,m,tf(m))}},Ze=async(e,t,n,i)=>{if(!await D(e))return{extensions:[],warnings:[]};let r=(await Sn.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,l)=>d.localeCompare(l)),a=new Map(i.entries.map(d=>[R(d.name),d])),o=new Map(i.entries.map(d=>[R(d.directory),d])),s=[],c=[];for(let d of r){let l=await Xk(e,d,t,n,a,o);l.warning&&s.push(l.warning),l.summary&&c.push(l.summary)}return{extensions:c.sort((d,l)=>d.name.localeCompare(l.name)),warnings:s.sort((d,l)=>d.localeCompare(l))}},Zk=rd(),Qk=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,eE=(e,t,n,i)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),a=i?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:Qk(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},tE=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},rf=e=>e.map(t=>tE(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),af=(e,t,n)=>{let i=R(e);return t.find(r=>(n===void 0||r.layer===n)&&R(r.name)===i)},nE=(e,t,n,i)=>n.find(r=>r.scope===t&&R(r.name)===R(e))?.activation_status??(i?"failed":"unknown"),of=(e,t,n,i,r)=>Zk.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await Sn.mkdtemp(Oe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=qe(import.meta.url,["../.."]);try{let s=await Be({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:La(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Je({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...rf(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[R(u.name),Hc(hn(c,{extensionName:u.name}))]));return{installed:zr(i,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await Sn.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),is=async(e,t,n,i)=>{let r=n.filter(c=>!c.managed),a=[...r].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),o=i,s=[];for(let c of a){let d=Oe.join(e,c.directory),l=await vn(d),u=$(),m={kind:"local",input:c.name,location:d};o=li(o,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await bn(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-r.length}},iE=(e,t)=>{let n=M(process.cwd(),t.path),i=Jt(n,process.cwd()),r=e==="global"?ji(process.cwd()):n,a=e==="global"?i.global:i.project;return{pm_root:n,scope:e,settings_root:r,selected_root:a,roots:i}},Jr=e=>{let t=[e.gh,e.github].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new g('Options "--gh" and "--github" must match when both are provided.',y.USAGE);return n[0]},rE=e=>Tk[e],aE=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=e==="install"?"source":"name",r=`${n} ${i}`,a=rE(e),o=`<${i}>`,s=`pm ${n} ${a} ${o}`;throw new g(`Action "${e}" requires ${r} input.`,y.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${i} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${i} target`}]}})},Vr=(e,t,n={})=>{let i=e?.trim();if(i)return i;if(t==="init")throw new g('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',y.USAGE);return aE(t,n)},oE=(e,t)=>{let n=new Set([...t.registrations.item_types.map(i=>({entry:i,count:i.types.length})),...t.registrations.item_fields.map(i=>({entry:i,count:i.fields.length}))].filter(({count:i})=>i>0).map(({entry:i})=>`${i.layer}:${R(i.name)}`));return e.loaded.filter(i=>(i.activation?.commands??[]).length>0).filter(i=>n.has(`${i.layer}:${R(i.name)}`)).map(i=>`extension_schema_narrow_activation:${i.layer}:${i.name}`).filter((i,r,a)=>a.indexOf(i)===r).sort((i,r)=>i.localeCompare(r))},sE=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(n)throw new g(n.message,y.USAGE)},cE=(e,t,n)=>{let i=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(i)?void 0:e},dE=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},lE=(e,t,n)=>{let i={ok:n,action:e.action,scope:e.scope,roots:dE(e),warnings:[...new Set(e.warnings)].sort((r,a)=>r.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(i,$k,{value:!0,enumerable:!1,configurable:!1}),i},rs=async(e,t,n)=>{let i=Jk(e,t);sE(i,t);let r=cE(e,i,t),a=Vk(t),o=iE(a,n),s={action:i,normalizedTarget:r,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},c={...s,withResult:(d,l=!0)=>lE(s,d,l)};return await WE(c)},uE=(e,t)=>{let n=t.vocabulary??"extension",i=e.target_path.replace(/\\/g,"/"),r=ld(i),a={package:`Install dependencies: cd ${r}, then run "npm install"`,extension:`Install type-check dependencies: cd ${r}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${r}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${r}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[a[n],...s,`Install the scaffold: ${le(n==="package"?["install","--project",i]:["extension","--install","--project",i])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},mE=async e=>{let{action:t,normalizedTarget:n,options:i,withResult:r}=e;if([Jr(i),i.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new g('Action "init" does not accept --gh/--github/--ref options.',y.USAGE);let a=Vr(n,t,i),o=await ip(a,i.vocabulary??"extension",i.capability,i.declarative===!0);return r({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:uE(o,i)})},pE=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:i,options:r,global:a,withResult:o}=e;if(t!==void 0)throw new g('Action "reload" does not accept a target argument.',y.USAGE);let s=await T(n.settings_root),c=La(),d=await Be({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:c,cache_bust:!0});i.push(...d.warnings);let l=await Je(d);i.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:r.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return r.watch===!0&&i.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(u)},fE=async e=>{let{normalizedTarget:t,scope:n,options:i,global:r,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new g('Action "catalog" does not accept a package target.',y.USAGE);return a(await Nm(n,r,i))},hE=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),_E=e=>({kind:"local",input:e.input,location:e.absolute_path}),gE=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),yE=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),wE=(e,t,n,i)=>e?hE(e,t):n.kind==="local"?_E(n):n.kind==="npm"?gE(n,i):yE(n,i),vE=(e,t,n,i)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:i}:Cm(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:i}:{installed_at:i,updated_at:i},bE=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r}=e,{validated:a,destinationDirectoryName:o}=t,s=await T(i.settings_root),c=await he(i.selected_root);r.push(...c.warnings);let d=Oe.join(i.selected_root,o),l=await D(d),u=await kn(a.directory,d);await Sn.mkdir(i.selected_root,{recursive:!0});let m=wE(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(w=>R(w.name)===R(a.manifest.name)),p=vE(f,a.manifest.version,m,$()),h=li(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...p,source:m}),_=Qp(s,a.manifest.name);return u||await Ip(a.directory,d),await Ep(d),await Sp(d),await bn(i.selected_root,h),_&&await lr(i.settings_root,s,"settings:write"),{settings:s,managedState:h,sourceRecord:m,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:_}},kE=async(e,t,n)=>{let i=n.filter(r=>R(r.name)===R(t)).flatMap(r=>r.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&i.length>0&&await oi(e.resolvedRoots.pm_root,i,e.warnings,"install:type-folder"),i},EE=(e,t,n,i,r)=>{let a=af(t,n.activation_failures,e.scope),o=nE(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:i.command_paths,registered_actions:i.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},SE=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t;return qp({selectedRoot:i.selected_root,settingsRoot:i.settings_root,destinationDirectory:Oe.join(i.selected_root,c),sourceDirectory:s.directory,scope:n},async()=>{let d=await bE(e,t),l=await Ze(i.selected_root,n,d.settings,d.managedState);r.push(...l.warnings);let u=await of(i.pm_root,Oe.dirname(i.selected_root),d.settings,l.extensions,a);r.push(...u.warnings);let m=await kE(e,s.manifest.name,u.item_type_registrations),f=Ap(s.manifest.name,u.installed),p=EE(e,s.manifest.name,u,f,m),h=u.contribution_inventories[R(s.manifest.name)];return h&&(d.managedState=await Tm(i.selected_root,d.managedState,s.manifest.name,h)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:p.activated,settings_changed:d.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:eE(s.manifest.name,d.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)})},xE=async e=>{let{options:t,global:n,warnings:i,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new g('Action "install all" does not accept --ref.',y.USAGE);let a=[],o=new Map;for(let s of await Mr()){let c=await ui(s),d=Oe.resolve(c),l=o.get(d);l===void 0&&(l=await rs(s,{...t,install:!0},n),o.set(d,l)),a.push({alias:s,result:l})}return i.push(...a.flatMap(s=>s.result.warnings)),r(jp(a,t.dryRun===!0),a.every(s=>s.result.ok))},IE=async(e,t,n)=>{let{resolvedRoots:i}=e,{bundledAliasName:r,bundledPackageName:a,installSource:o,sourceResolution:s}=await zp(t,n,e.options.ref,(await he(i.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${d.package}`)}let c=await Gm(o);try{let d=await vn(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),l=Lr(d.manifest.name),u=e.options.dryRun===!0||o.kind==="local"&&r===null?await Fp(c,Oe.join(i.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:u}):await Ko(i.settings_root,l,()=>SE(e,{validated:d,destinationDirectoryName:l,bundledAliasName:r,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},RE=async e=>{let t=Jr(e.options),n=t??Vr(e.normalizedTarget,e.action,e.options);return[t===void 0,Dm(n)].every(Boolean)?xE(e):IE(e,n,t)},AE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e;if(t!==void 0)throw new g('Action "adopt-all" does not accept a target argument.',y.USAGE);if(Jr(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new g('Action "adopt-all" does not accept --gh/--github/--ref options.',y.USAGE);let s=await T(i.settings_root),c=await he(i.selected_root);r.push(...c.warnings);let d=await Ze(i.selected_root,n,s,c.state);r.push(...d.warnings);let l=await is(i.selected_root,n,d.extensions,c.state),u=await Ze(i.selected_root,n,s,l.state);r.push(...u.warnings);let m=Wr(n,r,u.extensions,a);r.push(...m.warnings);let f=new Map(u.extensions.map(_=>[`${R(_.name)}:${R(_.directory)}`,_])),p=new Map(u.extensions.map(_=>[R(_.directory),_])),h=l.adopted_entries.map(_=>{let w=R(_.directory),v=f.get(`${R(_.name)}:${w}`)??p.get(w);return{..._,...sf(v)}});return o({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:l.already_managed_count,extensions:h,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},sf=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),CE=(e,t,n,i)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=mi(e,{forceGithub:!0,ref:i});if(r.kind!=="github")throw new g(`Invalid GitHub shorthand "${e}".`,y.USAGE);return{kind:"github",input:r.input,location:r.subpath??".",repository:r.repository,owner:r.owner,repo:r.repo,ref:r.ref,subpath:r.subpath}},TE=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o,withResult:s}=e,c=Vr(n,t,o),d=Jr(o),l=await T(r.settings_root),u=await he(r.selected_root);a.push(...u.warnings);let m=await Ze(r.selected_root,i,l,u.state);a.push(...m.warnings);let f=await Xp(m.extensions,c);if(!f)throw new g(`Installed extension "${c}" was not found in ${i} scope.`,y.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Oe.join(r.selected_root,f.directory),h=await vn(p),_=$(),w=CE(d,c,p,o.ref),v=li(u.state,{name:h.manifest.name,directory:f.directory,scope:i,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:_,updated_at:_,source:w});await bn(r.selected_root,v);let E=await Ze(r.selected_root,i,l,v);a.push(...E.warnings);let k=E.extensions.find(I=>R(I.name)===R(h.manifest.name))??E.extensions.find(I=>R(I.directory)===R(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...sf(k)})},cf=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o}=e,s=Vr(n,t,o),c=await T(r.settings_root),d=await he(r.selected_root);a.push(...d.warnings);let l=await Ze(r.selected_root,i,c,d.state);a.push(...l.warnings);let u=await Xp(l.extensions,s);if(!u)throw new g(`Installed extension "${s}" was not found in ${i} scope.`,y.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},$E=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:i,managedStateRead:r,candidate:a}=await cf(e),o=Oe.join(t.selected_root,a.directory);await Sn.rm(o,{recursive:!0,force:!0});let s={...r.state,updated_at:$(),entries:r.state.entries.filter(d=>R(d.name)!==R(a.name)&&R(d.directory)!==R(a.directory))};await bn(t.selected_root,s);let c=zk(i,a.name);return c&&await lr(t.settings_root,i,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},Gp=async e=>{let{action:t,resolvedRoots:n,warnings:i,global:r,withResult:a}=e,{settings:o,candidate:s}=await cf(e),c=t==="activate"?Qp(o,s.name):Hk(o,s.name);c&&await lr(n.settings_root,o,"settings:write");let d=t==="activate"?await of(n.pm_root,Oe.dirname(n.selected_root),o,[s],r).then(l=>(i.push(...l.warnings),af(s.name,l.activation_failures,e.scope))):void 0;return d&&i.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},d===void 0)},DE=(e,t,n,i,r,a)=>{let o=i==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=r?.adopted_entries.length??0,d=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},ns=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),OE=(e,t,n,i)=>{if(e!=="project"||t||!ns(i))return null;let r=n==="package"?"package":"extension";return`Global ${r} registrations are included in project diagnostics. For hermetic ${r} smoke tests, rerun pm ${r} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},PE=(e,t,n)=>{if(String(e??"").trim().length>0)throw new g('Action "doctor" does not accept a target argument.',y.USAGE);let i=[n.isolated,n.ignoreGlobal].includes(!0);if([i,t==="global"].every(Boolean))throw new g("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",y.USAGE);let r=fp(n.detail),a=n.trace===!0;if([a,r!=="deep"].every(Boolean))throw new g("--trace requires --detail deep with --doctor.",y.USAGE);return{isolated:i,detailMode:r,includeTrace:a}},LE=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let i=await is(e.resolvedRoots.selected_root,e.scope,t,n);return{state:i.state,fix:i}},NE=(e,t,n,i)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ns(i),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ns(i),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},ME=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=PE(t,n,a),u=await T(i.settings_root),m=await he(i.selected_root);r.push(...m.warnings);let f=await Ze(i.selected_root,n,u,m.state);r.push(...f.warnings);let{state:p,fix:h}=await LE(e,f.extensions,m.state),_=await Ze(i.selected_root,n,u,p);r.push(..._.warnings);let w=await Be({pmRoot:i.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Je({...w,loaded:w.loaded}),E=await Hp(i.pm_root);r.push(...E.warnings,...w.warnings),r.push(...up(w.failed)),r.push(...v.warnings),r.push(...mp(v.failed)),r.push(...pp(w,v)),r.push(...Cp(v,w)),r.push(...oE(w,v)),r.push(...Tp(v));let k=zr(_.extensions,w,v),I=_p(n,k,w.loaded.map(U=>({layer:U.layer,name:U.name})),w.failed.map(U=>({name:U.name})),w.disabled_by_flag);r.push(...I.warnings);let C=k.filter(U=>U.update_check_status==="failed").map(U=>`extension_update_check_failed:${U.name}`);r.push(...C);let S=Wr(n,r,k,a);r.push(...S.warnings);let b=[...S.warnings],O={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},P=hi(b),x=_i(),q=S.warning_codes,Se=OE(n,c,a.vocabulary,w),_e=DE(S.remediation,w.failed.length,v.failed.length,a.vocabulary,h,Se),pe=NE(n,c,a.vocabulary,w),Le={status:S.status,scope:n,warning_count:S.warning_count,warning_codes:q,total_extensions:k.length,managed_total:k.filter(U=>U.managed).length,enabled_total:k.filter(U=>U.enabled).length,active_total:k.filter(U=>U.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:k.filter(U=>U.runtime_active===!0).length,activation_status_totals:{ok:k.filter(U=>U.activation_status==="ok").length,failed:k.filter(U=>U.activation_status==="failed").length,not_loaded:k.filter(U=>U.activation_status==="not_loaded").length,unknown:k.filter(U=>U.activation_status==="unknown").length},unknown_capability_count:P.length,capability_contract_version:x.version,update_available_total:S.update_available_total,update_check_status_totals:S.update_check_status_totals,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:k.filter(U=>U.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Bo(w.failed),activation_failures:Bo(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:I.warnings.length,trace_enabled:l,isolation:pe,policy:O,remediation:_e},Di=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(U=>U.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:_.extensions.filter(U=>U.managed).length,adopted_extensions:[]},Nn={mode:d,summary:Le,triage:S,trace_enabled:l,capability_contract:x,capability_guidance:P,managed_state_fix:Di,author_manifest:E,isolation:pe,policy:w.policy};if(d==="deep"){let U=l?v.failed:v.failed.map(G=>{let{trace:Oi,...Pi}=G;return Pi});Nn.deep={warnings:b,warning_codes:q,capability_contract:x,capability_guidance:P,trace_enabled:l,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:k,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(G=>({layer:G.layer,directory:G.directory,name:G.name,version:G.version,entry:G.entry,priority:G.priority}))},activation:{failed:U,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:I.summary},l&&(Nn.deep.trace={activation_failures:v.failed.filter(G=>G.trace!==void 0).map(G=>({layer:G.layer,name:G.name,entry_path:G.entry_path,error:G.error,method:G.trace.method,command:G.trace.command,capability:G.trace.capability,missing_capability:G.trace.missing_capability,registration_index:G.trace.registration_index,expected_schema:G.trace.expected_schema,hint:G.trace.hint,received:G.trace.received}))})}return s(Nn)},jE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,c=await T(i.settings_root),d=await Be({pmRoot:i.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await Je(d);r.push(...d.warnings),r.push(...l.warnings);let u=ap(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",f=[...new Set(d.loaded.map(h=>a.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,_)=>h.localeCompare(_)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new g(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,y.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},FE=async(e,t,n)=>{let i=n,r=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await is(e.resolvedRoots.selected_root,e.scope,t,n),i=r.state),e.action==="manage"&&(i=await Pp(i,e.options.offline)),{state:i,fix:r}},UE=async(e,t,n)=>{let i=await Be({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Je({...i,loaded:i.loaded});return e.warnings.push(...i.warnings,...r.warnings),{installed:zr(n,i,r),failures:rf(r.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:i.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...i.warnings,...r.warnings])].length,policy:i.policy}}},HE=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},Bp=async e=>{let{action:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e,s=await T(i.settings_root),c=Uk(s.extensions.policy),d=await he(i.selected_root);r.push(...d.warnings);let l=await Ze(i.selected_root,n,s,d.state);r.push(...l.warnings);let{state:u,fix:m}=await FE(e,l.extensions,d.state),f=await Ze(i.selected_root,n,s,u);if(r.push(...f.warnings),t==="manage"&&a.offline===!0)for(let v of f.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=f.extensions.filter(E=>E.update_check_status==="failed").map(E=>`extension_update_check_failed:${E.name}`);r.push(...v)}let p=await UE(e,s,f.extensions),h=p.installed,_=Wr(n,r,h,a);r.push(..._.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:_,policy:c};return p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=HE(m,h)),o(w)},Jp={init:mE,install:RE,uninstall:$E,explore:Bp,manage:Bp,describe:jE,reload:pE,doctor:ME,catalog:fE,adopt:TE,"adopt-all":AE,activate:Gp,deactivate:Gp,migrate:Mp},zE=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),WE=e=>zE(e)?Ko(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Jp[e.action](e)):Jp[e.action](e);import{execFile as qE}from"node:child_process";import{realpath as GE}from"node:fs/promises";import df from"node:path";import{promisify as BE}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 JE=BE(qE),VE=32*1024*1024,KE=1e4,YE=["search/eval-queries.json"];function as(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function XE(e){return`'${e.replaceAll("'","'\\''")}'`}async function ZE(e,t=GE){return t(e).catch(()=>df.resolve(e))}async function Kr(e){let t=await Et(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 ZE(e),i=as(df.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=Cl.map(a=>`${i}/${as(a)}`);try{let{stdout:a}=await JE("git",["ls-files","-z","--",...r.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:VE,windowsHide:!0,timeout:KE}),o=new Set(YE.map(d=>`${i}/${d}`)),s=[...new Set(a.split("\0").filter(d=>d.length>0&&!o.has(as(d))))].sort((d,l)=>d.localeCompare(l)),c=r.filter(d=>s.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(d=>XE(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import lf from"node:path";import{realpath as QE}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 uf(e,t){let n=t===null?[]:await Dl(t,[lf.relative(t,lf.join(await QE(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function mf(e,t,n,i){if(t===null)return{audit:null,count:0,warnings:[]};let r=await cn(e,sn(n));if(r.status==="ok")return{audit:r,count:0,warnings:[]};let a=Math.max(1,r.missing_patterns.length+r.stale_patterns.length);return{audit:r,count:a,warnings:i?[`merge_fence_${r.status==="not_installed"?"missing":"drift"}:${a}`]:[]}}function pf(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}import{execFile as NS}from"node:child_process";import{randomUUID as MS}from"node:crypto";import{readdir as jS,realpath as Ct,stat as FS}from"node:fs/promises";import ie from"node:path";import{promisify as US}from"node:util";import eS from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b3ef9db1-1d20-5d88-927e-a08edf563cd5")}catch{}})();function ff(e,t,n){let i=zn(e,t);if(i.ok)return i.document;let r=structuredClone(e);for(let[a,o]of t.entries()){let s=/^\/metadata\/([^/]*)$/u.exec(o.path)?.[1],c=s!==void 0&&!Object.hasOwn(r.metadata,s.replaceAll("~1","/").replaceAll("~0","~"));if(c&&o.op==="remove")continue;let d=c&&o.op==="replace"?{...o,op:"add"}:o,l=zn(r,[d]);if(!l.ok)throw new g(`History union cannot rebase a scalar patch at ${n.branch} line ${n.line} (${n.op}), operation ${a+1} ${o.op} ${o.path}; preserve the source histories for manual recovery.`,y.CONFLICT,{code:"history_union_rebase_conflict",field:o.path,history_merge:{...n,patch_index:a,patch_path:o.path},nextSteps:["Preserve all three history inputs and both item snapshots. Review the named branch event against the merged replay state; do not drop the event or concatenate unchecked patches. After resolving the history and item deliberately, run pm history <id> --verify and pm merge reconcile --dry-run before committing."]});r=l.document}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]="425ef2aa-56fa-5d06-b8d0-316373ad2433")}catch{}})();var tS=Object.freeze({pm_item_scalar_missing:!0});function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function V(e){return e===void 0?tS:e}function At(e){return xe(A(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function os(e,t){let n=$e(e);if(n)throw new g(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let i=[];for(let[r,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(o)try{let s=JSON.parse(o);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");i.push(s)}catch{throw new g(`History merge input (${t}) contains invalid JSON at line ${r+1}.`,y.GENERIC_FAILURE)}}return i}function He(e){return A({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function nS(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&He(e[i])===He(t[i]);)i+=1;return i}function iS(e,t,n,i){let r=[...e,...n],a=new Map(r.map((u,m)=>[u,m])),o=new Map(r.map((u,m)=>[He(u),m])),s=r.map(()=>new Set);for(let u of[e,t]){let m=u.map(f=>a.get(f)??o.get(He(f)));for(let f=1;f<m.length;f+=1)m[f-1]!==m[f]&&s[m[f-1]].add(m[f])}let c=r.map(()=>0);for(let u of s)for(let m of u)c[m]+=1;let d=r.map((u,m)=>m).filter(u=>c[u]===0),l=[];for(;d.length>0;){d.sort((m,f)=>{let p=r[m],h=r[f],_=Lt(p.ts,h.ts),w=He(p),v=He(h);return _||Number(i.has(v))-Number(i.has(w))});let u=d.shift();l.push(r[u]);for(let m of s[u])c[m]-=1,c[m]===0&&d.push(m)}if(l.length!==r.length)throw new g("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",y.GENERIC_FAILURE);return l}function hf(e){return{entries:e,positions:new Map(e.map((t,n)=>[He(t),n])),index:-1,document:ir()}}function ms(e,t){let n=t??e.index;for(;e.index<n;){let i=zn(e.document,e.entries[e.index+1].patch);if(!i.ok)throw new g("History union cannot preserve a patch that does not apply in its original branch.",y.GENERIC_FAILURE);e.document=i.document,e.index+=1}return e.document}function _f(e,t){if(t!==void 0&&t>e.index+1)throw new g("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",y.GENERIC_FAILURE);return ms(e,t)}function rS(e,t,n){if(n===0)return;let i=hf(e),r=hf(t),a=ms(i,n-1);ms(r,n-1);let o=0,s=new Set([...yf,...wf]);return(c,d)=>{if(o++<n)return c.patch;let l=He(c),u=_f(i,i.positions.get(l)),m=_f(r,r.positions.get(l)),f=ar(c.patch).filter(v=>{let[E,k]=v.path.slice(1).split("/");return E!=="metadata"||!s.has(k)}),p=i.positions.get(l),h=ff(d,f,{branch:p===void 0?"theirs":"ours",line:(p??r.positions.get(l))+1,op:c.op}),_=kf(a.metadata,u.metadata,m.metadata,"ours","latest_document_update",String(u.metadata.updated_at),String(m.metadata.updated_at));for(let v of s)Object.hasOwn(_.merged,v)?h.metadata[v]=_.merged[v]:delete h.metadata[v];let w=rr({metadata:h.metadata,body:h.body});return eS.compare(d,w)}}function JN(e,t,n){let i=os(e,"base"),r=os(t,"ours"),a=os(n,"theirs"),o=[i,r,a].map(f=>f.filter(p=>p.op==="create"));if(o[0].length===0&&o.slice(1).every(f=>f.length>0)||o.some(f=>f.length>1)||new Set(o.flat().map(He)).size>1)throw new g("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",y.CONFLICT,{code:"item_identity_conflict"});let s=nS(r,a);if(s===r.length&&s===a.length)return{merged:Nt(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===a.length)return{merged:Nt(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:Nt(a),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:a.length-s,entries_total:a.length,reanchored:!1};let c=r.slice(s),d=new Set(c.map(He)),l=a.slice(s).filter(f=>!d.has(He(f))),u=iS(c,a.slice(s),l,d),m=or([...r.slice(0,s),...u],void 0,{continuousHashSurface:!0,projectPatch:rS(r,a,s)});if(m.skippedOps>0)throw new g(`History union cannot preserve ${m.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,y.GENERIC_FAILURE);return{merged:Nt(m.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:c.length,entries_from_theirs:l.length,entries_total:m.entries.length,reanchored:!0}}function ss(e,t){let n=$e(e);if(n)throw new g(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let i=[];for(let[r,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch{throw new g(`Relationship merge input (${t}) contains invalid JSON at line ${r+1}.`,y.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new g(`Relationship merge input (${t}) line ${r+1} is not a relationship event (eventId + sequence required).`,y.GENERIC_FAILURE);i.push(s)}return i}function Yr(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
24
|
+
`),Dr.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
25
|
+
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Dr.write(`
|
|
26
|
+
`),dw(n,!0)}finally{t.close()}}function em(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:To,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,i)=>n.localeCompare(i)):[]}}async function tm(e){let t=[],n=await Qu(e);for(let i of Xy){let r=ce.join(e,i),a=await D(r);if(!a){t.push({file_path:r,exists:a,has_guidance:!1,has_marker:!1});continue}let o=await Co.readFile(r,"utf8"),s=o.toLowerCase(),c=Zy.filter(l=>s.includes(l)),d=rw(o);t.push({file_path:r,exists:a,has_guidance:d||c.length>=Qy,has_marker:d,outdated:d&&Zu(o,n).changed})}return t}function Ut(e,t){e.includes(t)||e.push(t)}function uw(e,t){let n=em(e),i=JSON.stringify(n)!==JSON.stringify(t);return i&&(e.agent_guidance=t),{changed:i,state:t}}async function nm(e,t=ce.dirname(e)){let n=await D(e)?await Co.readFile(e,"utf8"):"",i=Zu(n,await Qu(t));return i.changed?(await Z(e,i.next_content),{changed:!0,warnings:await K({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function mw(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>hn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>hn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>hn(e.projectRoot,t.file_path))}}async function pw(e,t,n){return e?await tm(n):t}function ri(e,t,n){e.state={...e.state,...n,template_version:To,last_checked_files:t}}async function im(e,t){if(t.presentBefore)return;let n=await nm(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function fw(e,t){t||(e.warnings.push("agent_guidance:missing"),Ut(e.nextSteps,ai))}function hw(e,t){e.skipped=!0,ri(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ut(e.nextSteps,ai)}async function _w(e,t){await im(e,t),ri(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function gw(e,t){e.state.declined&&ri(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function yw(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ut(e.nextSteps,ai)}async function ww(e,t){if(e.prompted=!0,await lw(t.targetRelativePath)){await im(e,t),ri(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ri(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ut(e.nextSteps,ai)}function vw(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ut(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),Ut(e.nextSteps,ai)}async function bw(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(fw(n,t.presentBefore),n):t.mode==="skip"?(hw(n,t.checkedFiles),n):t.mode==="add"?(await _w(n,t),n):t.presentBefore?(gw(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(yw(n),n):t.interactive?(await ww(n,t),n):(vw(n),n)}async function rm(e){let t=sw(e.pm_root,e.cwd),n=await tm(t),i=cw(n,t),r=hn(t,i),a=n.map(l=>hn(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await bw(em(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:i,targetRelativePath:r,checkedFiles:a,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let l of n.filter(u=>u.outdated)){let u=await nm(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=uw(e.settings,s.state);n=await pw(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>hn(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),Ut(s.nextSteps,"pm init --agent-guidance add")),{summary:mw({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:r,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8289336-e833-5617-9a32-0a21f28f294e")}catch{}})();function oi(e){let t=/^extension_(disabled_)?pm_(min|max)_version_([a-z_]+):(project|global):([^:]+):(.+)$/u.exec(e);if(!t)return;let[,n,i,r,a,o,s]=t,c=s.split(":")[0].replace(i==="min"?"required=":"allowed=",""),d=r==="invalid"?`a valid pm_${i}_version instead of ${c}`:`pm ${i==="min"?">=":"<="} ${c}`;return n?`Package ${o} is disabled and requires ${d} before activation. After satisfying the bound, run ${le(["package","activate",o,`--${a}`])}.`:`Package ${o} requires ${d}. Use a compatible host or package version, or keep it disabled with ${le(["package","deactivate",o,`--${a}`])}.`}import _t from"node:fs/promises";import be from"node:path";import si from"node:fs/promises";import{createHash as kw}from"node:crypto";import om 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]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();var $o=new Set([void 0,...Pd]),sm=11,Ew="history-drift-cache.json";function cm(e){return om.join(e,"runtime",Ew)}async function Sw(e){try{let t=await si.readFile(cm(e),"utf8"),n=JSON.parse(t);return n.version!==sm||n.history_item_hash_version!==ir||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(i=>typeof i.chain_ok!="boolean"||typeof i.latest_hash_comparable!="boolean"||!$o.has(i.hash_algorithm)||!en.includes(i.item_hash_version)&&i.version_skew!==!0||i.chain_ok&&i.version_skew!==!0&&en.includes(i.item_hash_version)&&!i.latest_hash_comparable)?null:n}catch{return null}}function dm(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function lm(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[te]:[]])].sort((n,i)=>n.localeCompare(i));return{...e,driftedItems:t}}async function xw(e,t,n,i,r){let a=nn(e),o;try{o=await si.stat(a)}catch(d){return j(d)||r.unreadableStreams.push(te),!1}let s=r.missingStreams.length,c=await um({itemId:te,historyPath:a,stat:o,cached:t[te],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.versionSkew&&r.versionSkews.push(te),c.verification.chainOk||r.chainMismatches.push(te),n[te]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(r.missingStreams.splice(s),c.cacheDirty)}function Iw(e){return!$o.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!en.includes(e.item_hash_version)}async function Rw(e){let t=await si.readFile(e,"utf8"),n=kw("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let i=[],r=null;for(let m of t.split(/\r?\n/)){let f=m.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(p),r=p.after_hash}if(!r)return null;let a=kt(i),o=i.some(Iw),s=i[i.length-1],c=$o.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&en.includes(d),u=l?d:a.item_hash_version;return{latestAfterHash:r,hashAlgorithm:c?Re(s.hash_algorithm):void 0,identityDiscontinuities:Ld(i),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??ir}}function Aw(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function am(e,t,n){try{return await Rw(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function Cw(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function um(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Aw(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await am(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await am(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!Cw(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&en.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function mm(e,t,n,i){let r,a;try{r=Ot(e,t.id),a=await si.stat(r)}catch(d){return(j(d)?i.missingStreams:i.unreadableStreams).push(t.id),!1}let o=await um({itemId:t.id,historyPath:r,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:i});if(!o.verification)return o.cacheDirty;o.verification.identityDiscontinuities.length>0&&(i.identityDiscontinuities??=[]).push(...o.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),o.verification.versionSkew&&i.versionSkews.push(t.id),o.verification.chainOk||i.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,version_skew:o.verification.versionSkew,latest_hash_comparable:o.verification.latestHashComparable,item_hash_version:o.verification.itemHashVersion,hash_algorithm:o.verification.hashAlgorithm};let{body:s,...c}=t;return o.verification.latestHashComparable&&(Bd({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||i.hashMismatches.push(t.id)),o.cacheDirty}async function Tw(e,t){if(!(t.unreadableStreams.includes(te)||t.chainMismatches.includes(te)||t.versionSkews.includes(te)))try{let n=await Xd(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(te)}}async function pm(e,t){let n=dm();return await mm(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),lm(n)}async function Ht(e,t,n={}){let i=dm(),r=(await Sw(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:r,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await mm(e,l,c,i)&&(o=!0);let d=await xw(e,r,a,s,i);if(o||=d,await Tw(e,i),o||Object.keys(r).length!==Object.keys(a).length){let l=cm(e);try{await si.mkdir(om.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:sm,history_item_hash_version:ir,entries:a}))}catch{}}return lm(i)}import _n from"node:fs/promises";import Or 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]="6b4ef85f-d844-53e3-ba32-08b95377584a")}catch{}})();function fm(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:i,owner:r,created_at:a,ttl_seconds:o}=n;return typeof i!="string"||typeof r!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:i,owner:r,created_at:a,ttl_seconds:o,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function $w(e,t,n){let i=fm(t);if(i===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 r=Date.parse(i.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-r,o=Math.floor(a/1e3),s=a>i.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function hm(e,t,n){let i=$w(e,t,n);if(i.detail!=="active")return i;let r=fm(t),a=await yd(r);return a==="unknown"?i:{detail:a==="dead"?"owner_dead":"active",entry:{...i.entry,owner_state:a,pid:r.pid,...a==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function Dw(e,t,n){let i=await wd(e,"gc");if(i===null)return!1;try{let r;try{r=await _n.readFile(e,"utf8")}catch(a){if(j(a))return!0;throw a}if(r!==t)return!1;n&&await vd(e,t);try{await _n.unlink(e)}catch(a){if(!j(a))throw a}return!0}finally{await i()}}function Ow(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 _m(e,t){let n=t??Date.now(),i=Or.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await _n.readdir(i)).filter(o=>o.endsWith(".lock")).sort()}catch(o){if(j(o))return r;throw o}for(let o of a){let s;try{s=await _n.readFile(Or.join(i,o),"utf8")}catch(l){if(j(l))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c,entry:d}=await hm(o,s,n);Ow(r,c,d)}return r}async function Pw(e,t,n,i,r,a,o){if(!t.dryRun){try{if(!await Dw(n,a,o.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${r}`),e.retained.push(i),e.entries.push(o);return}}catch{e.warnings.push(`lock_remove_failed:${r}`),e.retained.push(i),e.entries.push(o);return}if(t.hooks?.onWrite){let s=await t.hooks.onWrite(n);e.warnings.push(...s)}}e.removed.push(i),e.entries.push(o)}async function gm(e,t){let{hooks:n}=t,i=t.now??Date.now(),r=Or.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},o;try{o=(await _n.readdir(r)).filter(s=>s.endsWith(".lock")).sort()}catch(s){if(j(s))return a;throw s}for(let s of o){a.scanned+=1;let c=Or.join(r,s),d=`locks/${s}`;if(n?.onRead){let m=await n.onRead(c);a.warnings.push(...m)}let l;try{l=await _n.readFile(c,"utf8")}catch(m){if(j(m)){a.scanned-=1;continue}a.warnings.push(`lock_unreadable:${s}`),a.retained.push(d),a.entries.push({file:s,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await hm(s,l,i);if(u.detail==="unparseable_json"){a.warnings.push(`lock_unparseable:${s}`),a.retained.push(d),a.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){a.warnings.push(`lock_invalid_timestamp:${s}`),a.retained.push(d),a.entries.push(u.entry);continue}if(u.detail==="active"){a.retained.push(d),a.entries.push(u.entry);continue}await Pw(a,t,c,d,s,l,u.entry)}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]="0e576e9d-5aa3-5d54-8acf-23e4f18b432f")}catch{}})();var Lw=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 Do(e){if(typeof e!="string")return;let t=e.trim();for(let n of Lw)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Oo(e){let t={};for(let n of e){let i=Do(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function ym(e){return Object.values(Oo(e))}import In from"node:fs/promises";import Oe 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]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Nw=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function gn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Bi(t.extensionName));for(let _ of t.extensionNames??[])n.add(Bi(_));let i=_=>n.size===0||n.has(Bi(_)),r=(_,w)=>wm(_.filter(v=>i(v.name)).map(w)),a=(_,w)=>wm(_.filter(v=>i(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:d,services:l,renderers:u,hooks:m}=e,f=a(o.relationship_kinds??[],_=>_.definitions.map(w=>w.kind)),p=u.overrides.filter(_=>i(_.name)&&((_.commands?.length??0)>0||_.resultDiscriminator!==void 0)).map(_=>({format:_.format,commands:[..._.commands??[]],result_discriminator:_.resultDiscriminator!==void 0})).sort((_,w)=>_.format.localeCompare(w.format)),h=r(o.assurance_providers??[],_=>_.definition.id);return{capabilities:ud(e,t),commands:r(o.commands,_=>_.command),command_overrides:r(s.overrides,_=>_.command),command_handlers:r(s.handlers,_=>_.command),hooks:Nw.filter(([_])=>m[_].some(w=>i(w.name))).map(([,_])=>_),flag_commands:r(o.flags,_=>_.target_command),item_types:a(o.item_types,_=>_.types.map(w=>w.name)),item_fields:a(o.item_fields,_=>_.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:a(o.migrations,_=>typeof _.definition.id=="string"?[_.definition.id]:[]),profiles:r(o.profiles,_=>_.profile.name),importers:r(o.importers,_=>_.importer),exporters:r(o.exporters,_=>_.exporter),search_providers:r(o.search_providers,_=>_.definition.name),vector_store_adapters:r(o.vector_store_adapters,_=>_.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:r(c.overrides,_=>_.command),service_overrides:r(l.overrides,_=>_.service),renderer_overrides:r(u.overrides,_=>_.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:d.overrides.filter(_=>i(_.name)).length,preflight_ownership:d.overrides.filter(_=>i(_.name)).map(_=>({commands:[..._.commands??[]]}))}}function wm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import lv from"node:path";import{mkdir as uv}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]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Mw=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function jw(e){let t=Mw.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Fw(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function vm(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,i=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let c=jw(s);if(c===void 0)continue;let d=r.get(c)??{count:0,examples:[]};d.count+=1,d.examples.length<i&&d.examples.push(s),r.set(c,d)}let a=[];for(let[o,s]of r.entries()){if(s.count<n)continue;let c=Fw(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:Yc(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as Em}from"node:crypto";import wn from"node:fs/promises";import vn 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]="09d88765-6283-5287-b293-43300251833f")}catch{}})();function dt(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Sm(e){let t=dt(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function xm(e,t){let n=Lo(e),i=dt(t,"migrationScope");return`auto-${Em("sha256").update(JSON.stringify({scope:i,request:n})).digest("hex").slice(0,20)}`}function Lo(e){let t=e.kind==="rename-type"?{kind:e.kind,from:dt(e.from,"source"),to:dt(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:se(dt(e.from,"source")),to:se(dt(e.to,"target")),...e.type===void 0?{}:{type:dt(e.type,"type")}}:{kind:e.kind,from:se(dt(e.from,"source")),to:se(dt(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Uw(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Hw(e,t,n){let i=Ie(t.schema),r=Uw(n);return Ke(e,i.files[r],Te[r])}function Im(e,t){return vn.join(e,"transactions","schema",`${t}-plan.json`)}function Pr(e){return e.length===0?null:JSON.parse(e)}async function yn(e){let t=await B(e);return{exists:t!==null,raw:t??""}}async function Rm(e,t){t.exists?await Z(e,t.raw):await wn.rm(e,{force:!0})}function zw(e,t,n){let i=it(e),r=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=i.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return wt(i);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);i.definitions.push({...i.definitions[r],name:t.to})}else r>=0&&i.definitions.splice(r,1);return wt(i)}function Ww(e,t,n){let i=Kt(e),r=i.fields.findIndex(o=>o.key===t.from),a=i.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(a>=0)return Yt(i);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=i.fields[r];i.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&i.fields.splice(r,1);return Yt(i)}function qw(e,t,n){let i=Xt(e),r=i.statuses.findIndex(o=>o.id===t.from),a=i.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(a>=0)return Zt(i);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);i.statuses.push({...i.statuses[r],id:t.to})}else r>=0&&i.statuses.splice(r,1);return Zt(i)}function Gw(e,t,n){return t.kind==="rename-type"?zw(e,t,n):t.kind==="rename-field"?Ww(e,t,n):qw(e,t,n)}function xt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function No(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function bn(e){return Array.isArray(e)?e.map(t=>No(t)).filter(t=>t!==void 0):[]}function Bw(e,t){for(let n of bn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(i=>xt(i,t)));for(let n of bn(e.type_workflows))n.type=xt(n.type,t)}function Jw(e,t){for(let i of bn(e.definitions))i.default_status=xt(i.default_status,t);let n=No(e.workflow);if(n)for(let[i,r]of Object.entries(n))n[i]=xt(r,t);for(let i of bn(e.type_workflows))Array.isArray(i.allowed_transitions)&&(i.allowed_transitions=i.allowed_transitions.map(r=>Array.isArray(r)?r.map(a=>xt(a,t)):r))}function Vw(e,t){for(let n of bn(e.definitions)){for(let i of["required_create_fields","required_create_repeatables"])Array.isArray(n[i])&&(n[i]=n[i].map(r=>xt(r,t)));for(let i of["options","command_option_policies"])for(let r of bn(n[i])){let a=i==="options"?"key":"option";r[a]=xt(r[a],t)}}}function Kw(e,t){let n=No(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let i=t.kind==="rename-type"?"type":"status";n[i]=xt(n[i],t)}function Po(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let i=n;return t.kind==="rename-type"?Bw(i,t):t.kind==="rename-field"?Vw(i,t):Jw(i,t),Kw(i,t),`${JSON.stringify(i,null,2)}
|
|
27
|
+
`}function Am(e,t){if(t.kind==="rename-type"){let i=it(e).definitions;return{source:i.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:i.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let i=Kt(e).fields;return{source:i.some(r=>r.key===t.from),target:i.some(r=>r.key===t.to)}}let n=Xt(e).statuses;return{source:n.some(i=>i.id===t.from),target:n.some(i=>i.id===t.to)}}function Yw(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function Xw(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function Cm(e,t){let n=Lo(t.request),i=t.migrationId===void 0?xm(n,t.migrationScope??"plan"):Sm(t.migrationId),r=e.map(c=>Xw(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),a=Em("sha256").update(JSON.stringify({migrationId:i,request:n,items:r})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=r.filter(c=>!o.has(c.id));return Object.freeze({migration_id:i,request:n,fingerprint:a,affected_item_count:r.length,pending_item_count:s.length,skipped_completed_count:r.length-s.length,items:Object.freeze(s)})}async function Zw(e){let t=H(e.settings,F()),n=[...new Set(Object.values(t.type_to_folder))],i=await mr(e.pmRoot,n),r=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},a=i?await cl({pmRoot:e.pmRoot,expectedSourceCursor:i.source_cursor,query:r}):null;return a?{items:a.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await rt(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function Qw(e,t){let n=await B(Im(e,t));if(n===null)return null;try{let i=JSON.parse(n);if(i.schema_version!==1||i.plan.migration_id!==t||!Array.isArray(i.plan.items))throw new TypeError("invalid plan envelope");return i.plan}catch(i){throw new g(`Stored schema migration plan "${t}" is invalid: ${Pc(i)}`,y.GENERIC_FAILURE)}}async function ev(e,t){let n=Im(e,t.migration_id);await wn.mkdir(vn.dirname(n),{recursive:!0});let i={schema_version:1,plan:t,created_at:new Date().toISOString()};await Z(n,`${JSON.stringify(i,null,2)}
|
|
28
|
+
`)}function tv(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function nv(e){let t=await ge(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new g(`Schema migration item "${e.id}" no longer exists.`,y.NOT_FOUND);return(await ye(t,{schema:e.settings.schema})).document.metadata}function bm(e,t,n){let i=n==="forward"?t.from:t.to,r=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==i.toLowerCase())throw new TypeError(`Schema migration expected type "${i}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==i.toLowerCase())throw new TypeError(`Schema migration expected status "${i}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let a=e.metadata;if(Object.prototype.hasOwnProperty.call(a,r)&&!Object.prototype.hasOwnProperty.call(a,i))return[];if(!Object.prototype.hasOwnProperty.call(a,i)||Object.prototype.hasOwnProperty.call(a,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return a[r]=a[i],delete a[i],[i,r]}function km(e){return{id:e.id,inspect:async()=>{let t=await yn(e.filePath),n=Am(t.raw,e.request),i=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:i?"applied":"pending",...i?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await yn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await yn(e.filePath);return await Z(e.filePath,Gw(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Rm(e.filePath,{exists:t.exists,raw:t.raw})}}}function iv(e){return{id:e.stepId,inspect:async()=>{let t=await yn(e.filePath);return{state:Po(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await yn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await yn(e.filePath);return await Z(e.filePath,Po(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Rm(e.filePath,{exists:t.exists,raw:t.raw})}}}function rv(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await T(e.pmRoot),n=H(t,F()).type_to_folder,i=await nv({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=Yw(i,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await T(e.pmRoot),n=H(t,F()).type_to_folder,i=await ot({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(r){return{changedFields:bm(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:i.changedFields}},compensate:async()=>{let t=await T(e.pmRoot),n=H(t,F()).type_to_folder;await ot({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(i){return{changedFields:bm(i,e.request,"reverse")}}})}}}async function av(e){let t=await Qw(e.pmRoot,e.migrationId);if(t){if(!tv(t.request,e.request))throw new g(`Schema migration id "${e.migrationId}" already belongs to a different request.`,y.CONFLICT);return{plan:t,stored:!0}}let n=await Zw({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Cm(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function ov(e){let t=Am(await B(e.schemaPath)??"",e.request);if(!t.source)throw new g(`Schema migration source "${e.request.from}" is not a custom definition.`,y.NOT_FOUND);if(t.target)throw new g(`Schema migration target "${e.request.to}" already exists.`,y.CONFLICT);await ev(e.pmRoot,e.plan)}async function sv(e){let t=Ie(e.settings.schema),n=[...new Set([["types",Te.types],["fields",Te.fields],["workflows",Te.workflows]].map(([r,a])=>Ke(e.pmRoot,t.files[r],a)).filter(r=>r!==e.schemaPath))];try{let r=vn.join(e.pmRoot,"templates"),a=await wn.readdir(r,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>vn.join(r,o.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||!j(r))throw r}n.sort((r,a)=>r.localeCompare(a));let i=[];for(let r of n){let a=await B(r);a!==null&&Po(a,e.request)!==a&&i.push({filePath:r,beforeRaw:a})}return{paths:n,snapshots:i}}async function cv(e){for(let t of e.snapshots){let n=await wn.readFile(t.filePath,"utf8"),i=vn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Ja({pmRoot:e.pmRoot,author:e.author,documentPath:i,before:Pr(t.beforeRaw),after:Pr(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${i}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function dv(e,t,n){let i=Lo(e),r=M(process.cwd(),n.path);await ne(r);let a=t.migrationId===void 0?xm(i,await wn.realpath(r)):Sm(t.migrationId),o=await T(r),s=z(t.author,o.author_default),c=await av({pmRoot:r,settings:o,migrationId:a,request:i}),d=c.plan;if(t.dryRun===!0)return{...d,action:i.kind,applied:!1,recovered:!1,migrated_item_count:0};let l=Hw(r,o,i),u=await B(l)??"";c.stored||await ov({pmRoot:r,schemaPath:l,request:i,plan:d});let m=await sv({pmRoot:r,schemaPath:l,settings:o,request:i}),f=[km({id:"stage-schema",filePath:l,request:i,phase:"stage"}),...m.paths.map((w,v)=>iv({filePath:w,request:i,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>rv({pmRoot:r,id:w.id,request:i,author:s,force:t.force===!0})),km({id:"retire-source",filePath:l,request:i,phase:"retire"})],p=await uu({pmRoot:r,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),h=await wn.readFile(l,"utf8"),{historyPath:_}=await Ja({pmRoot:r,author:s,documentPath:vn.relative(r,l).replaceAll("\\","/"),before:Pr(u),after:Pr(h),op:"schema_migration",idempotencyKey:`${d.migration_id}:${d.fingerprint}`,message:`${i.kind}: ${i.from} -> ${i.to}; affected=${d.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await cv({pmRoot:r,author:s,settings:o,request:i,plan:d,snapshots:m.snapshots}),{...d,action:i.kind,applied:!0,recovered:p.recovered,migrated_item_count:d.affected_item_count,workspace_history_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]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var BD=[...Hi,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Lr="schema-types",Tm="schema-statuses",$m="schema-fields";function It(e){return on({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function KD(e,t,n){let i=M(process.cwd(),n.path);await lt(i);let r;try{r=Fa({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new g(f instanceof Error?f.message:String(f),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=Ke(i,o.files.types,Te.types),c=[],d=z(t.author,a.author_default),l=je(a),u=await re(i,Lr,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms),m;try{let f=await B(s),p;try{p=it(f)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.GENERIC_FAILURE)}try{Xc(r,p);let h=new Map,_=H(a,F());for(let[w,v]of Object.entries(_.type_to_folder)){let E=v.trim().toLowerCase();E.length>0&&!h.has(E)&&h.set(E,w)}Zc(r,p,h)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}m=qi(p,r),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await It({pmRoot:i,filePath:s,raw:wt(m.file),op:"schema:add-type",author:d,settings:a}),await ci(i,[m.definition],c,"schema:add-type-folder"),c.push(...await K({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await Dm(i,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:Rt(c),generated_at:$()}}async function lt(e){await ne(e)}async function Dm(e,t){try{let n=await Nl(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function Rt(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function mv(e,t,n,i){let r=H(t,F()),a=i.trim().toLowerCase();return(await rt(e,t.item_format,r.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function pv(e,t,n,i){let r=H(t,F()),a=fe(n),o=se(i);return(await rt(e,t.item_format,r.type_to_folder,[],n)).filter(s=>{let c=typeof s.status=="string"?s.status:"";return(a.alias_to_id.get(se(c))??se(c))===o}).length}async function fv(e,t,n,i,r){if(r.length===0||Ha.has(r))return;let a=await pv(t,n,i,r);a>0&&e.push(`items_using_status:${a}`);let o=hv(i.workflow,r);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function hv(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&se(n)===t).map(([n])=>n)}async function YD(e,t,n){let i=M(process.cwd(),n.path);await lt(i);let r=await T(i),a=Ie(r.schema),o=Ke(i,a.files.types,Te.types),s=[],c=z(t.author,r.author_default),d=je(r),l=await re(i,Lr,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await B(o),f;try{f=it(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=Qc(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await mv(i,r,a,p);h>0&&s.push(`items_using_type:${h}`)}await It({pmRoot:i,filePath:o,raw:wt(u.file),op:"schema:remove-type",author:c,settings:r}),s.push(...await K({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await l()}return u.removed&&await Dm(i,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:o,definitions:u.file.definitions.length},warnings:Rt(s),generated_at:$()}}function Mo(e,t){return Ke(e,t.files.statuses,Te.statuses)}function Nr(e,t){return Ke(e,t.files.fields,Te.fields)}function Om(e,t){return Ke(e,t.files.types,Te.types)}async function ci(e,t,n,i){for(let r of t){let a=Nc(r.folder??Lc(r.name)),o=lv.join(e,a);await D(o)||(await uv(o,{recursive:!0}),n.push(...await K({path:o,scope:"project",op:i})))}}function jo(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function _v(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function gv(e){let t=new Map;for(let n of e){let i=se(n.id);if(i.length!==0){t.set(i,i);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let a=se(r);a.length>0&&!t.has(a)&&t.set(a,i)}}}return t}async function XD(e,t,n){let i=M(process.cwd(),n.path);await lt(i);let r;try{r=sd({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=Mo(i,o),c=fe(o);try{za(r,c.alias_to_id)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let d=_v(c.by_id.get(r.id));if((r.roles??d?.roles??[]).length===0)throw new g(`Status "${r.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,y.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${Vt(r.id)}" --role active`,`pm schema add-status "${Vt(r.id)}" --role blocked`]});let l=[],u=z(t.author,a.author_default),m=je(a),f=await re(i,Tm,a.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),p;try{let h=await B(s),_;try{_=Xt(h)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=gv(_.statuses);try{za(r,w)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.USAGE)}p=cd(_,r,d),await It({pmRoot:i,filePath:s,raw:Zt(p.file),op:"schema:add-status",author:u,settings:a}),l.push(...await K({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:Rt(l),generated_at:$()}}async function ZD(e,t,n){let i=M(process.cwd(),n.path);await lt(i);let r=await T(i),a=Ie(r.schema),o=Mo(i,a),s=[],c=z(t.author,r.author_default),d=je(r),l=await re(i,Tm,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await B(o),f;try{f=Xt(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=dd(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=se(u.definition?.id??e);await fv(s,i,r,a,p),await It({pmRoot:i,filePath:o,raw:Zt(u.file),op:"schema:remove-status",author:c,settings:r}),s.push(...await K({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await l()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:o,statuses:u.file.statuses.length},warnings:Rt(s),generated_at:$()}}function Pm(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function yv(e,t,n){return{...Pm(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function Lm(e){return{id:e.id,source:Ha.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Nm(e,t,n){let i=e.toLowerCase();return n.has(i)?"extension":t.has(i)?"custom":"builtin"}function wv(){let e=new Map,t=F();for(let n of t?.item_types??[]){let i=n.types;if(Array.isArray(i))for(let r of i){if(typeof r!="object"||r===null||Array.isArray(r))continue;let a=r.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function vv(e){let t=fe(e),n=[],i=[];for(let r of t.definitions){let a=Lm(r);a.source==="builtin"?n.push(a):i.push(a)}return{builtin:n,custom:i}}async function di(e){let t=M(process.cwd(),e.path);await lt(t);let n=await T(t),i=Ie(n.schema),r=Ke(t,i.files.types,Te.types),a=Mo(t,i),o=H(n,F()),s=wv(),c=new Set((n.item_types?.definitions??[]).map(d=>d.name.trim().toLowerCase()).filter(d=>d.length>0&&!s.has(d)));return{pmRoot:t,typesPath:r,statusesPath:a,byType:o.by_type,customNames:c,extensionProvenance:s,schema:i}}async function QD(e){let t=await di(e),n=[],i=[],r=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Nm(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Pm(s);c==="extension"?r.push(d):c==="custom"?i.push(d):n.push(d)}let a=vv(t.schema),o=Gi(t.schema).definitions.map(jo);return{action:"list",builtin:n,custom:i,extension:r,counts:{builtin:n.length,custom:i.length,extension:r.length,total:n.length+i.length+r.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:$()}}async function eO(e,t){let n=(e??"").trim();if(n.length===0)throw new g("Type name must not be empty.",y.USAGE);let i=await di(t),r=Object.values(i.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!r)throw new g(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${Vt(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:yv(r,Nm(r.name,i.customNames,new Set(i.extensionProvenance.keys())),i.extensionProvenance.get(r.name.toLowerCase())),file:{path:i.typesPath},generated_at:$()}}async function tO(e,t){let n=se(e);if(n.length===0)throw new g("Status id must not be empty.",y.USAGE);let i=await di(t),r=fe(i.schema),a=r.alias_to_id.get(n)??n,o=r.by_id.get(a);if(!o)throw new g(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${Vt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:Lm(o),file:{path:i.statusesPath},generated_at:$()}}async function nO(e,t,n){let i=M(process.cwd(),n.path);await lt(i);let r;try{r=nd({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=Nr(i,o),c=[],d=Yi(r.key);d&&c.push(`custom_field_mcp_input_collision:${d.field}:${d.property}:${d.owner}:use=${d.nested_path}`);let l=z(t.author,a.author_default),u=je(a),m=await re(i,$m,a.locks.ttl_seconds,l,!!t.force,u.force_required_for_stale_lock,a.locks.wait_ms),f;try{let p=await B(s),h;try{h=Kt(p)}catch(_){throw new g(_ instanceof Error?_.message:String(_),y.GENERIC_FAILURE)}f=id(h,r),await It({pmRoot:i,filePath:s,raw:Yt(f.file),op:"schema:add-field",author:l,settings:a}),c.push(...await K({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:Rt(c),generated_at:$()}}async function bv(e,t,n,i){let r=H(t,F());return(await rt(e,t.item_format,r.type_to_folder,[],n)).filter(a=>{let o=a[i];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function iO(e,t,n){let i=M(process.cwd(),n.path);await lt(i);let r=await T(i),a=Ie(r.schema),o=Nr(i,a),s=[],c=z(t.author,r.author_default),d=je(r),l=await re(i,$m,r.locks.ttl_seconds,c,!!t.force,d.force_required_for_stale_lock,r.locks.wait_ms),u;try{let m=await B(o),f;try{f=Kt(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=rd(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=se(u.definition?.key??e),h=se(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let _=await bv(i,r,a,h);_>0&&s.push(`items_using_field:${_}`)}await It({pmRoot:i,filePath:o,raw:Yt(u.file),op:"schema:remove-field",author:c,settings:r}),s.push(...await K({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await l()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:o,fields:u.file.fields.length},warnings:Rt(s),generated_at:$()}}async function rO(e){let t=await di(e),n=Gi(t.schema).definitions.map(jo);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Nr(t.pmRoot,t.schema)},generated_at:$()}}async function aO(e,t){let n=se(e);if(n.length===0)throw new g("Field key must not be empty.",y.USAGE);let i=await di(t),r=Gi(i.schema).by_key.get(n);if(!r)throw new g(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${Vt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:jo(r),file:{path:Nr(i.pmRoot,i.schema)},generated_at:$()}}async function oO(e,t,n){let i=M(process.cwd(),n.path);await lt(i);let r;try{let h=td(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${ed.join(", ")}.`);r=h}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let a=await T(i),o=Ie(a.schema),s=Om(i,o),c=[],d=z(t.author,a.author_default),l=je(a),u=[],m=[],f,p=await re(i,Lr,a.locks.ttl_seconds,d,!!t.force,l.force_required_for_stale_lock,a.locks.wait_ms);try{let h=await B(s),_;try{_=it(h)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=_;for(let v of Ua(r)){let E=qi(w,v);w=E.file,(E.replaced?m:u).push(E.definition.name)}f=w.definitions.length,await It({pmRoot:i,filePath:s,raw:wt(w),op:"schema:apply-preset",author:d,settings:a}),await ci(i,Ua(r),c,"schema:apply-preset-folder"),c.push(...await K({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:r,registered:u,replaced:m,file:{path:s,definitions:f},warnings:Rt(c),generated_at:$()}}function kv(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new g("--min-count must be a positive integer (>= 1).",y.USAGE);return e}async function sO(e,t){let n=M(process.cwd(),t.path);await lt(n);let i=await T(n),r=Ie(i.schema),a=Om(n,r),o=kv(e.minCount),s=H(i,F()),c=(await rt(n,i.item_format,s.type_to_folder,[],r)).map(v=>typeof v.title=="string"?v.title:""),d=vm(c,{minCount:o}),l=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=it(await B(a))}catch(E){throw new g(E instanceof Error?E.message:String(E),y.GENERIC_FAILURE)}return p=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:l,generated_at:$()}}let h=z(e.author,i.author_default),_=je(i),w=await re(n,Lr,i.locks.ttl_seconds,h,!!e.force,_.force_required_for_stale_lock,i.locks.wait_ms);try{let v=await B(a),E;try{E=it(v)}catch(I){throw new g(I instanceof Error?I.message:String(I),y.GENERIC_FAILURE)}let k=E;for(let I of d){if(I.shadows_builtin){f.push({name:I.name,reason:"shadows_builtin"});continue}let C;try{C=Fa({name:I.name})}catch{f.push({name:I.name,reason:"invalid_type_token"});continue}let S=qi(k,C);k=S.file,(S.replaced?m:u).push(S.definition.name)}p=k.definitions.length,await It({pmRoot:n,filePath:a,raw:wt(k),op:"schema:infer-types",author:h,settings:i}),await ci(n,k.definitions.filter(I=>u.includes(I.name)||m.includes(I.name)),l,"schema:infer-types-folder"),l.push(...await K({path:a,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:d,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:Rt(l),generated_at:$()}}import Mm from"node:fs/promises";import Fo 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]="9cf5a9e7-4a66-5e72-80a2-f8a9b5b6e412")}catch{}})();function Ce(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function R(e){return e.trim().toLowerCase()}function Mr(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let i=t.length;for(;i>n&&t[i-1]==="-";)i-=1;let r=t.slice(n,i);if(r.length===0)throw new g("Extension manifest name must resolve to a non-empty directory name.",y.USAGE);if(r==="."||r==="..")throw new g('Extension manifest name must not resolve to "." or "..".',y.USAGE);return r}function Uo(e){return Vc(e)}async function Ev(e){try{let t=JSON.parse(await Mm.readFile(Fo.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(i=>typeof t.scripts?.[i]=="string")}}catch{return{has_build_script:!1}}}async function Sv(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new g(`Extension entry file is missing at "${t}".`,y.USAGE);let i=await Ev(n.source_root),r=i.package_name?`pm package install npm:${i.package_name}`:void 0,a=n.source_input??n.source_root;return new g(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm package install copies GitHub repositories without running package scripts${i.has_build_script?", and this package declares a build or publish script":""}. ${r?`Try "${r}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,y.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:r?[r,`pm package install ${n.source_root}`]:[`pm package install ${n.source_root}`],nextSteps:r?[`Retry with ${r}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm package install npm:<package-name>."],recovery:{attempted_command:`pm install ${a}`,normalized_args:["install",a],...r?{next_best_command:r}:{}}})}async function kn(e,t={}){let n=Fo.join(e,"manifest.json");if(!await D(n))throw new g(`Extension manifest is missing at "${n}".`,y.USAGE);let i;try{i=JSON.parse(await Mm.readFile(n,"utf8"))}catch(o){throw new g(`Failed to parse extension manifest at "${n}": ${xv(o)}`,y.USAGE)}let r=Uo(i);if(!r)throw new g(`Extension manifest at "${n}" is invalid.`,y.USAGE);let a=Fo.resolve(e,r.entry);if(!me(e,a))throw new g(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await D(a))throw await Sv(r,a,t);if(!await Kc(e,a))throw new g(`Extension entry "${r.entry}" resolves outside extension directory after symlink resolution.`,y.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:r}}function xv(e){return e instanceof Error?e.message:String(e)}import Ho from"node:fs/promises";import Iv 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]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();var Rv=".managed-extensions.json",jr=1;function li(e){return Iv.join(e,Rv)}function Av(){return{version:jr,updated_at:$(),entries:[]}}function ui(e){return[...e].sort((t,n)=>{let i=t.scope.localeCompare(n.scope);if(i!==0)return i;let r=t.name.localeCompare(n.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function jm(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function ve(e){return typeof e=="string"?e:void 0}function Cv(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Tv(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:ve(t.name),package:ve(t.package),version:ve(t.version),repository:ve(t.repository),owner:ve(t.owner),repo:ve(t.repo),ref:ve(t.ref),subpath:ve(t.subpath),commit:ve(t.commit)}}function $v(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Cv(t))return null;let n=Tv(t.source);if(!n)return null;let i=Bc(t.contributions);return i===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Ce(t.capabilities),contributions:i,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:ve(t.last_update_check_at),last_update_remote_commit:ve(t.last_update_remote_commit),last_update_remote_version:ve(t.last_update_remote_version),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:ve(t.update_error)}}function Dv(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==jr||!Array.isArray(t.entries))return null;let n=[];for(let i of t.entries){let r=$v(i);r&&n.push(r)}return{version:jr,updated_at:ve(t.updated_at)??$(),entries:ui(n)}}async function he(e){let t=li(e),n=Av();try{let i=await Ho.readFile(t,"utf8"),r=JSON.parse(i),a=Dv(r);if(!a)throw new g(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(i){if(i instanceof g)throw i;if(typeof i=="object"&&i!==null&&"code"in i&&j(i))return{path:t,state:n,warnings:[]};throw new g(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,y.GENERIC_FAILURE)}}async function En(e,t){let n=li(e),i={version:jr,updated_at:$(),entries:ui(t.entries)};await Ho.mkdir(e,{recursive:!0}),await Ho.writeFile(n,`${JSON.stringify(i,null,2)}
|
|
29
|
+
`,"utf8")}function mi(e,t){let n=e.entries.filter(i=>R(i.name)!==R(t.name)&&R(i.directory)!==R(t.directory));return n.push(t),{...e,updated_at:$(),entries:ui(n)}}async function Fm(e,t,n,i){let r=t.entries.find(o=>R(o.name)===R(n));if(!r)return t;let a=mi(t,{...r,contributions:i});return await En(e,a),a}import{execFile as Wv}from"node:child_process";import J from"node:fs/promises";import Jo from"node:os";import N from"node:path";import{fileURLToPath as qv}from"node:url";import{promisify as Gv}from"node:util";import Bv from"npm-package-arg";import{extract as Jv,list as Vv}from"tar";import Ov from"node:fs/promises";import Ue 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]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var Pv="PM_CLI_PACKAGE_ROOT",Um={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Lv=new Set(["*","all"]);function zo(){let e=[],t=process.env[Pv];return typeof t=="string"&&t.trim().length>0&&e.push(Ue.resolve(t.trim())),e.push(Ge(import.meta.url,["../../.."])),[...new Set(e)]}async function pi(e){let t=e.trim().toLowerCase(),n=await zm(t);if(n)return n;let i=Um[t];if(!i)return null;for(let r of zo()){let a=Ue.join(r,".agents","pm","extensions",i.legacy_extension_directory);if(await D(Ue.join(a,"manifest.json")))return a}return null}function Hm(e){return Lv.has(e.trim().toLowerCase())}function Nv(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Mv(e,t){let n=await Ov.readdir(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!i.name.startsWith("pm-"))continue;let r=Ue.join(e,i.name);if(!await D(Ue.join(r,"package.json")))continue;let a=await zi(r),o=a.aliases&&a.aliases.length>0?a.aliases:[Nv(i.name)];for(let s of o){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:i.name,package_root:r,package_name:a.package_name??null})}}}async function Wo(){let e=new Map;for(let t of zo()){let n=Ue.join(t,"packages");await D(n)&&await Mv(n,e)}for(let[t,n]of Object.entries(Um))if(!e.has(t))for(let i of zo()){let r=Ue.join(i,"packages",n.package_directory);if(await D(Ue.join(r,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:r,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Fr(){return(await Wo()).map(e=>e.alias)}async function zm(e){let t=e.trim().toLowerCase();return(await Wo()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function Wm(e){let t=await zm(e);return t?(await zi(t)).package_name??null:null}async function qm(e){let t=await pi(e);if(!t)return null;try{let n=await Wi(t);return n.length!==1?null:(await kn(n[0])).manifest.name}catch{return null}}function jv(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Fv(e,t,n,i,r,a){let o=i==="global"?"--global":"--project",s=Object.fromEntries(ja.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>r.has(c))||a.has(Ue.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:jv(e),media:e.catalog?.media}}}async function Gm(e,t,n={}){let i=Jt(M(process.cwd(),t.path),process.cwd()),r=e==="global"?i.global:i.project,a=await he(r),o=new Set(a.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Ue.resolve(m.source.location))),s=new Set(a.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],d=new Map;for(let m of await Wo()){let f=Ue.resolve(m.package_root),p=d.get(f)??[];p.push(m),d.set(f,p)}for(let m of d.values()){let f=m[0],p=m.map(_=>_.alias).sort((_,w)=>_.localeCompare(w)),h=await zi(f.package_root);c.push(Fv(h,f,p,e,s,o))}let l=Hv(n.fields),u=l?c.map(m=>zv(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:ja.filter(m=>m!=="extensions"),packages:u}}var Uv=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function Hv(e){if(e===void 0)return;let t=Il(e);if(t.length===0)throw new g("Package catalog --fields requires a comma-separated list of field names",y.USAGE);let n=t.filter(i=>!Uv.has(i));if(n.length>0)throw new g(`Unknown package catalog --fields value(s): ${n.join(", ")}`,y.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function zv(e,t){let n={};for(let i of t)i==="category"?n[i]=e.catalog?.category??null:i==="display_name"?n[i]=e.catalog?.display_name??null:n[i]=e[i]??null;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]="fc993281-a2a0-59e8-9f4a-e520f1b94f3b")}catch{}})();var Jm=Gv(Wv),Hr="@unbrained/pm-cli",Kv={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},qo;async function Vm(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let i=N.resolve(t);for(;;){let r=N.join(i,"node_modules",...n.split("/")),a=N.join(r,"package.json");if(await D(a))try{let s=JSON.parse(await J.readFile(a,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:r}}catch{return null}let o=N.dirname(i);if(o===i)return null;i=o}}function Go(e,t,n){let i=e.split("/").map(d=>d.trim()).filter(d=>d.length>0);if(i.length<2)return null;let r=i[0],a=i[1].replace(/\.git$/i,"");if(r.length===0||a.length===0)return null;let o=i.slice(2),s,c;return o[0]==="tree"&&o.length>=2?(s=o[1],c=o.slice(2).join("/")):o.length>0&&(c=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:r,repo:a,repository:`https://github.com/${r}/${a}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function Yv(e,t,n){let i=e.slice(4).trim();if(i.length===0)throw new g('npm package source must include a package spec after "npm:".',y.USAGE);if(t)throw new g('Options "--gh/--github" cannot be combined with npm: package sources.',y.USAGE);if(n)throw new g('Option "--ref" cannot be combined with npm: package sources.',y.USAGE);return{kind:"npm",input:e,spec:i}}function fi(e,t={}){let n=e.trim();if(n.length===0)throw new g("Extension source is required for --install.",y.USAGE);let i=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return Yv(n,t.forceGithub===!0,i);let r=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return Go(s,n,i)}catch{return null}})();if(r)return r;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=Go(a,n,i);if(!o)throw new g(`Invalid GitHub source "${n}".`,y.USAGE);return o}if(t.forceGithub){let o=Go(n,n,i);if(!o)throw new g(`Invalid GitHub shorthand "${n}".`,y.USAGE);return o}if(/^https?:\/\//i.test(n))throw new g(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,y.USAGE);return{kind:"local",input:n,absolute_path:N.resolve(process.cwd(),n)}}async function Ur(e,t=Jm,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(i){let r=typeof i=="object"&&i!==null&&"stderr"in i?String(i.stderr):"",a=r.trim().length>0?r.trim():i instanceof Error?i.message:String(i);throw new g(`Git command failed: git ${e.join(" ")}
|
|
30
|
+
${a}`,y.GENERIC_FAILURE)}}function Vo(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function Ko(e=process.platform){return e==="win32"}async function Km(e,t,n=Jm,i=process.platform,r=process.env){let a=Vo(i),o=Object.fromEntries(Object.entries(r).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(a,e,{cwd:t,encoding:"utf8",env:o,shell:Ko(i)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",d=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new g(`npm command failed: ${a} ${e.join(" ")}
|
|
31
|
+
${d}`,y.GENERIC_FAILURE)}}function Ym(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Xm(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function Xv(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function Zv(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return Xv(e)||t.includes("not found")}function Qv(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function eb(e){let t=Ym(e),n=Qv(t),i=t.replace(/^.*\//,""),r=n?`github.com/unbraind/${i}`:void 0,a=r?`pm package install --project ${r}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:a?[a,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:a?[`Try ${a} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...r&&a?{fallback_candidates:[{source:r,command:a,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:a}:{}}}}}function tb(e,t){if(!Zv(t))return null;let n=eb(e);return new g(n.message,y.NOT_FOUND,n.context)}async function Zm(e){if(N.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=N.resolve(process.cwd(),e);return await D(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=qv(t);return await D(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=N.resolve(process.cwd(),e);if(await D(t))return t}return null}async function nb(e){let t=await Zm(e);if(t)return t;let n=ib(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function ib(e,t=process.cwd()){let n="@file:",i=e.lastIndexOf(n);if(!Xm(e))return e;let r=e.slice(0,i),a=e.slice(i+n.length);if(a.startsWith("//")&&!a.startsWith("///"))return e;if(!a.startsWith("/"))return`${r}@${N.resolve(t,a)}`;let o;try{o=decodeURIComponent(new URL(`file:${a}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${r}@${s}`}function Bm(e,t){let n=N.resolve(e,t),i=N.relative(e,n);if(i.length===0||i===".."||i.startsWith(`..${N.sep}`)||N.isAbsolute(i))throw new g("npm pack reported a package archive outside its isolated destination.",y.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function rb(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function ab(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let i=rb(n,t);return i?[i]:[]})}function ob(e,t){let n=t?.trim().toLowerCase(),i=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(i.length===1)return i[0];if(e.length!==1)return;let r=e[0],a=r.name??r.key;return n&&a!==void 0&&a.trim().toLowerCase()!==n?void 0:r}function sb(e,t,n){let i;try{i=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new g("npm pack did not report a tarball filename.",y.GENERIC_FAILURE);return{tarball:Bm(t,o)}}let r=ab(i),a=ob(r,n);if(!a)throw new g("npm pack --json returned an unsupported or ambiguous package receipt.",y.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${r.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:Bm(t,a.filename),package:a.name??a.key,version:a.version}}async function cb(e){return db(e,Km)}async function db(e,t){let n=await Zm(e.spec);if(n){if((await J.stat(n)).isFile()&&Qm(n))return Bo(n);let a=N.join(n,"package.json"),o=await D(a)?JSON.parse(await J.readFile(a,"utf8")):{};return{directory:await zr(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let i=await J.mkdtemp(N.join(Jo.tmpdir(),"pm-npm-package-source-")),r=N.join(i,"pack");await J.mkdir(r,{recursive:!0});try{let a=await nb(e.spec),o=await t(["pack",a,"--json","--pack-destination",r]),s=sb(o,r,Xm(e.spec)?void 0:Ym(e.spec));if(!await D(s.tarball))throw new g("npm pack did not create its reported package archive.",y.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await Bo(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await J.rm(i,{recursive:!0,force:!0})}}}}catch(a){throw await J.rm(i,{recursive:!0,force:!0}),tb(e.spec,a)||a}}function Qm(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ut(e){throw new g(e,y.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function lb(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ut(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let i=e.path,r=i.split("/");(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||r.some(a=>a===".."))&&ut(`Local package archive contains an escaping path: "${i}".`),r[0]!=="package"&&ut(`Local package archive entry "${i}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ut(`Local package archive link "${i}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ut(`Local package archive entry "${i}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ut(`Local package archive entry "${i}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ut(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),i==="package/package.json"&&(n.packageJsonEntries+=1)}async function Bo(e,t=Kv){(await J.stat(e)).size>t.maxArchiveBytes&&ut(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await J.mkdtemp(N.join(Jo.tmpdir(),"pm-local-package-archive-")),i=N.join(n,"extract");await J.mkdir(i,{recursive:!0});let r={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Vv({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:d=>{if(a===void 0)try{lb(d,t,r)}catch(l){a=l}}}),a!==void 0)throw a;r.packageJsonEntries!==1&&ut(`Local package archive must contain exactly one package/package.json entry; found ${r.packageJsonEntries}.`),await Jv({file:e,cwd:i,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=N.join(i,"package"),s=N.join(o,"package.json"),c=JSON.parse(await J.readFile(s,"utf8"));return await ub(o),{directory:await zr(o,e),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{await J.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await J.rm(n,{recursive:!0,force:!0}),o}}async function ub(e,t=Km){let n=N.join(e,"package.json");if(!await D(n))return;let i;try{i=JSON.parse(await J.readFile(n,"utf8"))}catch{return}if(typeof i!="object"||i===null)return;let r=i,a=gb(r),o=mb(r);if(a.length===0&&!o)return;let s={...i};delete s.devDependencies;let c={...s};pb(c),await J.writeFile(n,`${JSON.stringify(c,null,2)}
|
|
32
|
+
`,"utf8");try{await Promise.all([J.rm(N.join(e,"package-lock.json"),{force:!0}),J.rm(N.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await fb(e)}finally{await J.writeFile(n,`${JSON.stringify(s,null,2)}
|
|
33
|
+
`,"utf8")}}function mb(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Hr in t)return!0;return!1}function pb(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let i={...n};delete i[Hr],Object.keys(i).length===0?delete e[t]:e[t]=i}}async function fb(e){let t=Ge(import.meta.url,["../../.."]),[n,i]=Hr.split("/"),r=N.join(e,"node_modules",n),a=N.join(r,i);await J.mkdir(r,{recursive:!0}),await J.rm(a,{recursive:!0,force:!0}),await J.symlink(t,a,hb(process.platform))}function hb(e){return e==="win32"?"junction":"dir"}function _b(e,t){if(e.startsWith("-"))throw new g(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,y.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let i=n.charCodeAt(0);return i<=31||i===127||"&|;()`\"'".includes(n)}))throw new g(`Extension runtime dependency "${e}" has an unsafe version specifier.`,y.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Bv.resolve(e,t)}catch{throw new g(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,y.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function gb(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[i,r]of Object.entries(n)){if(i===Hr||typeof r!="string"||r.trim().length===0||t.has(i))continue;let a=r.trim();t.set(i,_b(i,a))}return[...t.values()]}async function zr(e,t){let n=await Wi(e);if(n.length===1)return n[0];if(n.length>1){let i=n.map(r=>N.relative(e,r).replaceAll(N.sep,"/")).sort((r,a)=>r.localeCompare(a));throw new g(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${i.join(", ")}`,y.USAGE)}throw new g(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,y.USAGE)}async function yb(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(N.posix.join(".agents/pm/extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extensions",t.subpath)),n.push(N.posix.join(".custom/pm-extension",t.subpath)));for(let r of n){let a=N.resolve(e,r);if(me(e,a)&&await D(N.join(a,"manifest.json")))return{directory:a,resolved_subpath:r}}if(await D(N.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let i=await zr(e,t.input);return{directory:i,resolved_subpath:N.relative(e,i).replaceAll(N.sep,"/")}}function wb(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function vb(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!wb(n))return new g(t,y.NOT_FOUND);let i=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?N.resolve(a.trim()):"";qo?.key!==o&&(qo={key:o,aliases:await Fr()}),i=qo.aliases}catch{}let r=[`Retry with pm package install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${i.join(", ")}`];return new g(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,y.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm package install npm:${n}`,"pm package catalog --project --json"],nextSteps:r,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm package install npm:${n}`}})}async function ep(e){if(e.kind==="local"){let i;try{i=await J.stat(e.absolute_path)}catch{throw await vb(e)}if(i.isFile()&&Qm(e.absolute_path)){let a=await Bo(e.absolute_path);return{source:e,directory:a.directory,source_root:N.dirname(a.directory),resolved_subpath:N.relative(N.dirname(a.directory),a.directory).replaceAll(N.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!i.isDirectory())throw new g(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,y.USAGE);let r=await zr(e.absolute_path,e.input);return{source:e,directory:r,source_root:e.absolute_path}}if(e.kind==="npm"){let i=await cb(e);return{source:e,directory:i.directory,source_root:N.dirname(i.directory),cleanup:i.cleanup,resolved_subpath:N.relative(N.dirname(i.directory),i.directory).replaceAll(N.sep,"/"),npm_package:i.package,npm_version:i.version}}let t=await J.mkdtemp(N.join(Jo.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await Ur(n);let i=await Ur(["-C",t,"rev-parse","HEAD"]),r=await yb(t,e);return{source:e,directory:r.directory,source_root:t,resolved_subpath:r.resolved_subpath,commit:i,cleanup:async()=>{await J.rm(t,{recursive:!0,force:!0})}}}catch(i){throw await J.rm(t,{recursive:!0,force:!0}),i}}async function Sn(e,t){if(!await D(e)||!await D(t))return!1;let[n,i]=await Promise.all([J.realpath(e),J.realpath(t)]);return n===i}import hi from"node:fs/promises";import _i 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]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var Yo=1,zt="2026.6.24",bb=">=22.18.0",kb={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},tp=new Set([...Gc.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(qc).map(e=>e.toLowerCase()),"scaffold"]),Eb="^6.0.0",Sb="^22.0.0",rp=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],Qe=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function np(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function ap(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function op(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var xb={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},ip=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],sp={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Ib={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Rb={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},Ab={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},cp="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Cb={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},Tb={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},$b={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},Db={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function dp(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function lp(e,t){return e==="schema"?$b[t]:e==="profile"?Db[t]:Tb[t]}function Ob(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),i=0;for(;t[i]?.toLowerCase()==="starter";)i+=1;let r=t[i]?.toLowerCase(),a=i>0&&(i===t.length||r!==void 0&&tp.has(r));return`${(tp.has(n)||a?["starter",...t]:t).join(" ")} ping`}function up(e){let t=e,n=`${e}s`,i=e.replace(/-/g,""),r=i===t?[]:[i],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(r)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Pb(e,t,n){let i=`${e}-search`,r=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(i)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(r)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,d=e.replace(/-/g,""),l=d===s?[]:[d],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(l)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...up(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Lb(e,t,n){let i=n==="hooks",r=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",d=n==="parser",l=n==="preflight",u=n==="services",m=Ib[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,_=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=i?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});",""]:[],E=r?Xo(e,t,"search",m):[],k=a?Xo(e,t,"importers",m):[],I=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...np(ap({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});",""]:[],C=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...np(op(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});",""]:[],S=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});",""]:[],b=d?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});",""]:[],O=l?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});",""]:[],P=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...r?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...rp,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...d?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});","",...v,...E,...k,...I,...C,...S,...b,...O,...P,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
|
|
34
|
+
`)}function Nb(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let i=`${e.replace(/-/g," ")} items`;return[t,`${i} import`,`${i} export`]}return[t]}var Mb={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},jb={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function Fb(e,t,n){let i=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...i?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...i?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Ub(e,t,n){let i=[],r=[...Fb(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,d=e,l=`${e}s`,u=e.replace(/-/g,""),m=u===d?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":i.push("defineAfterCommandHook"),r.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":i.push("defineSearchProvider","defineVectorStoreAdapter"),r.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":i.push("defineExporter","defineImporter"),r.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":i.push("defineItemField","defineItemType","defineMigration"),r.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(d)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(l)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":i.push("defineProjectProfile"),r.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...up(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":i.push("defineRendererOverride"),r.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":i.push("defineParserOverride"),r.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":i.push("definePreflightOverride"),r.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),a.push(" preflights: [preflightOverride],");break;case"services":i.push("defineServiceOverride"),r.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:i,definitions:r,blueprintFields:a}}function Hb(e,t,n){let i=Ub(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...i.builderImports].sort((r,a)=>r.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...i.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...i.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
|
|
35
|
+
`)}function Xo(e,t,n,i){if(n==="commands")return[];let r=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,d=`${e.replace(/-/g,"_")}_note`,l=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(r)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(r)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(ap({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:d,migrationId:l})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(op(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function zb(e,t,n){let i=n==="parser",r=JSON.stringify([...sp[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...rp,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(zt)},`," },",` target: { pmVersion: ${JSON.stringify(zt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${r});`,` assert.deepEqual(report.manifest?.capabilities, ${r});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...i?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...Qe,"});","",...Xo(e,t,n,r)].join(`
|
|
36
|
+
`)}function Wb(e,t,n){let i=dp(n,"package"),r=lp(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",i,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Mb[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",cp,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${jb[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...r,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Yo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${zt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
37
|
+
`)}function qb(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function Gb(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function Bb(e,t,n,i){let r=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&r.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&r.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(i.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(i.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&r.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&r.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(i.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(i.itemTypeName)},`,` folder: ${JSON.stringify(i.itemTypeFolder)},`,` aliases: ${JSON.stringify(i.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(i.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&r.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(i.itemTypeName)}, folder: ${JSON.stringify(i.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&r.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&r.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&r.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&r.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),r}function Jb(e,t,n){let i=[];return t==="renderers"&&i.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&i.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&i.push(" api.registerPreflight(preflightOverride);"),t==="services"&&i.push(' api.registerService("output_format", outputService);'),t==="hooks"&&i.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&i.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&i.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&i.push(" api.registerProfile(starterProfile);"),t==="importers"&&i.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),i}function Vb(e,t,n,i="commands",r=!1){let a=`pm-${e}`,o=sp[i],s=Nb(e,t,i),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:Yo,pm_min_version:zt,trusted:!0,sandbox_profile:"strict",permissions:{...kb},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
|
|
38
|
+
`,d=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Pb(e,t,i),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
|
|
39
|
+
`),l=`${JSON.stringify(xb,null,2)}
|
|
40
|
+
`,u=Rb[i],m=dp(i,"package"),f=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:bb},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${zt}`},devDependencies:{"@types/node":Sb,typescript:Eb},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
|
|
41
|
+
`,p=Lb(e,t,i),h=Ab[i],_=["node_modules/","*.log","*.tsbuildinfo",""].join(`
|
|
42
|
+
`),w=qb(e),v=["```ts",`import { ${Gb(i)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Bb(e,t,i,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Jb(t,i,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],E=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,cp,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Cb[i],...lp(i,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${zt}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${Yo}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${zt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
|
|
43
|
+
`);return{"package.json":f,"manifest.json":c,"index.ts":r?Hb(e,t,i):d,"index.test.ts":r?zb(e,t,i):p,"tsconfig.json":l,".gitignore":_,"README.md":r?Wb(a,t,i):E}}async function mp(e,t="extension",n="commands",i=!1){let r=n.trim().toLowerCase();if(!ip.includes(r))throw new g(`Unknown scaffold capability "${n}". Supported capabilities: ${ip.join(", ")}.`,y.USAGE);let a=r;if(i&&t!=="package")throw new g("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",y.USAGE);let o=i?"declarative":"imperative",s=e.trim(),c=_i.resolve(process.cwd(),s),d=Mr(_i.basename(c)).replace(/^(?:pm-)+/u,""),l=Ob(d),u=Vb(d,l,t,a,i),m=!1;if(await D(c)){if(!(await hi.stat(c)).isDirectory())throw new g(`Scaffold target "${c}" exists and is not a directory.`,y.CONFLICT)}else await hi.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let _=_i.join(c,p);if(await D(_)&&await hi.readFile(_,"utf8")!==h)throw new g(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,y.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let _=_i.join(c,p);if(await D(_)){f.push({path:p,status:"unchanged"});continue}await hi.mkdir(_i.dirname(_),{recursive:!0}),await hi.writeFile(_,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:d,package_name:`pm-${d}`,command_name:l,invocation_command:`pm ${l}`,capability:a,style:o,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function pp(e,t){return`${e}:${R(t)}`}function Kb(e,t){let n=[];for(let[i,r]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of r){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(d=>t.has(R(d.name))))continue;let c=s.at(-1);n.push({command:o,surface:i,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(d=>({name:d.name,layer:d.layer,winner:d===c}))})}}return n.sort((i,r)=>i.command.localeCompare(r.command)||i.surface.localeCompare(r.surface))}function fp(e,t,n){let i=new Set(n.failed.map(d=>pp(d.layer,d.name))),r=[...t.loaded.map(d=>({name:d.name,layer:d.layer,version:d.version,activation_status:i.has(pp(d.layer,d.name))?"failed":"ok",surfaces:gn(n,{extensionName:d.name})})),...t.failed.map(d=>({name:d.name,layer:d.layer,version:"unknown",activation_status:"not_loaded",surfaces:gn(n,{extensionName:d.name})}))].sort((d,l)=>d.name.localeCompare(l.name)||d.layer.localeCompare(l.layer)),a=typeof e=="string"?R(e):null,o=a===null?null:new Set(t.loaded.filter(d=>R(d.name)===a||typeof d.source_package=="string"&&R(d.source_package)===a||(d.source_aliases??[]).some(l=>R(l)===a)).map(d=>R(d.name)).concat(a)),s=o===null?r:r.filter(d=>o.has(R(d.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:gn(n,c),command_ownership:Kb(n,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]="573b0fd6-f003-55d8-8f49-c2a5e81cbc31")}catch{}})();function Zo(e){return e.map(({layer:t,name:n,error:i})=>({layer:t,name:n,error:i}))}function Wr(e,t,n){let i=R(t),r=n.trim();if(i.length===0||r.length===0)return;let a=e.get(i)??new Set;a.add(r),e.set(i,a)}function Yb(e){let t=new Map,n=new Map;for(let i of e.registrations.commands)Wr(t,i.name,i.command),Wr(n,i.name,i.action);for(let i of e.commands.handlers)Wr(t,i.name,i.command);for(let i of e.commands.overrides)Wr(t,i.name,i.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function hp(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function Xb(e){let{enabled:t,normalizedName:n,loadedNames:i,loadFailedNames:r,activationFailedNames:a}=e;return t?r.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:i.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function qr(e,t,n){let i=new Set(t.loaded.map(c=>R(c.name))),r=new Set(t.failed.map(c=>R(c.name))),a=new Set(n.failed.map(c=>R(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=Yb(n);return e.map(c=>{let d=R(c.name),l=hp(o.get(d)),u=hp(s.get(d)),m={...l?{command_paths:l}:{},...u?{action_paths:u}:{}},f=Xb({enabled:c.enabled,normalizedName:d,loadedNames:i,loadFailedNames:r,activationFailedNames:a});return{...c,...f,...m}})}function Zb(e){let t=0,n=0,i=0;for(let r of e)if(r.startsWith("extension_policy_")){if(t+=1,r.startsWith("extension_policy_violation_")){n+=1;continue}r.startsWith("extension_policy_blocked_")&&(i+=1)}return{warning_count:t,violation_count:n,blocked_count:i}}function de(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var yp=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function Qb(e){return yp.has(Sp(e))}function _p(e){return e==="project"||e==="global"}function wp(e){let t=e.split(":"),n=t[0];if(!n||!yp.has(n))return null;let i=t.at(-4),r=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!_p(i)||!_p(a)||!r||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:i,name:r},displaced:{layer:a,name:o}}}function ek(e){let t=new Set;for(let n of e){let i=wp(n);i&&(t.add(i.winner.name),t.add(i.displaced.name))}return[...t].sort((n,i)=>n.localeCompare(i))}function Qo(e,t){let n=e.filter(Qb);if(n.length===0)return null;let i=ek(n);return`Extension registration collisions or handler/override overlaps detected.${i.length>0?` Conflicting extensions: ${i.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function tk(e,t,n,i){let r=t.map(u=>wp(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(r.length===0)return;let a=e==="global"?"--global":"--project",o=de(i,"deactivate"),s=`${de(i,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[R(u.name),u])),d=new Map;for(let u of r)for(let m of[u.winner.name,u.displaced.name]){let f=R(m);d.set(f,(d.get(f)??0)+1)}let l=[...d.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],_=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${o} ${p} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[..._].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:r.length,extension_count:d.size,next_best_command:s,collisions:r,remediation_candidates:l}}function vp(e){let t=[];for(let n of e){let i=n.error.toLowerCase();(i.includes("cannot find package '@unbrained/pm-cli'")||i.includes('cannot find module "@unbrained/pm-cli"')||i.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(i.includes("cannot use import statement outside a module")||i.includes("to load an es module")||i.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}function bp(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let i of t){if(!i||typeof i.name!="string")continue;let r=i.trace?.missing_capability??i.trace?.capability;typeof r=="string"&&r.trim().length>0&&n.push(`extension_capability_missing:${i.name}:${r.trim().toLowerCase()}`)}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function kp(e,t){let n=[];for(let i of md(e.loaded,t))for(let r of i.unused)n.push(`extension_capability_unused:${i.layer}:${i.name}:${r}`);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}var nk=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${de(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Mi.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${de(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${de(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${de(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${de(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function ik(e){let{normalizedWarnings:t,options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:d,updateAvailableTotal:l}=e,u=t.map(oi).filter(f=>f!==void 0),m={options:n,scope:i,scopeFlag:r,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let f=Qo(t,{deactivate:`${de(n,"deactivate")} <name> ${r}`,doctor:`${de(n,"doctor")} ${r} --detail deep --trace`});f&&u.push(f);for(let p of nk)p.matches(t,m)&&u.push(p.build(m))}return s>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${de(n,"manage")} ${r} --fix-managed-state (or ${de(n,"adopt-all")} ${r}, ${de(n,"adopt")} <name> ${r}, or reinstall via ${de(n,"install")} ${r} <source>).`),d>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${de(n,"manage")} ${r} to request update checks.`),l>0&&u.push(`Update available managed extensions via ${de(n,"install")} ${r} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${de(n,"manage")} ${r} after extension changes.`),u}function Gr(e,t,n,i={}){let r=[...new Set(t)].sort((b,O)=>b.localeCompare(O)),a=n.filter(b=>b.managed).length,o=n.filter(b=>b.enabled).length,s=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,d=n.filter(b=>b.managed===!1),l=d.filter(b=>gp(b)).map(b=>b.name).sort((b,O)=>b.localeCompare(O)),u=d.filter(b=>!gp(b)).map(b=>b.name).sort((b,O)=>b.localeCompare(O)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let f=m.failed,p=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,O])=>`extension_update_health_partial_coverage:${b}:${O}`),_=h.length>0,w=_?"partial":"full",v=[...new Set([...r,...h])].sort((b,O)=>b.localeCompare(O)),E=[...new Set(v.map(b=>Sp(b)))].sort((b,O)=>b.localeCompare(O)),k=Zb(v),I=e==="global"?"--global":"--project",C=tk(e,r,n,i),S=ik({normalizedWarnings:v,options:i,scope:e,scopeFlag:I,updateCheckFailedTotal:f,policyWarningCount:k.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:E,warnings:v,policy_warning_count:k.warning_count,policy_violation_count:k.violation_count,policy_blocked_count:k.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:_,unmanaged_loaded_extension_count:d.length,unmanaged_loaded_extensions:d.map(b=>b.name).sort((b,O)=>b.localeCompare(O)),unmanaged_expected_extension_count:l.length,unmanaged_expected_extensions:l,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:S,...C?{collision_plan:C}:{}}}function Ep(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new g(`Invalid --detail value "${e}". Expected summary or deep.`,y.USAGE)}function Sp(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function gi(e){let t=new Set,n=[];for(let i of e){let r=(()=>{let a=Sc(i);return a?[a]:xc(i)})();for(let a of r){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function yi(){return{version:ji.version,capabilities:[...ji.capabilities],legacy_aliases:{...ji.legacy_aliases}}}function gp(e){let t=R(e.name),n=R(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function xp(e,t,n,i,r){if(e!=="project"||r)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(d=>d.active).map(d=>R(d.name)))].sort((d,l)=>d.localeCompare(l)),o=[...new Set(n.filter(d=>d.layer==="project").map(d=>R(d.name)))].sort((d,l)=>d.localeCompare(l)),s=new Set(i.map(d=>R(d.name))),c=a.filter(d=>!o.includes(d)&&!s.has(d)).sort((d,l)=>d.localeCompare(l));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import Ip 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]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function wi(e,t,n,i){let r=Ip.relative(e,n);if(r!==""&&!me(e,n)||n===t||me(t,n))return!1;let a=r.split(Ip.sep);return a.includes(".git")?!1:i?!a.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as rk}from"node:crypto";import ie from"node:fs/promises";import ak from"node:os";import X from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var Rp=3,ok=120,Ap=250,sk=12e4,ck=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),Cp=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,Tp=e=>ck.has(String(Cp(e))),Br=(e,t)=>Cp(e)===t,$p=e=>new Promise(t=>{setTimeout(t,e)}),Dp=async e=>{let t=X.join(e,"package.json");await D(t)||await ie.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
|
|
44
|
+
`,"utf8")},Op=async e=>{let t=Ge(import.meta.url,["../../.."]),n=X.join(e,"node_modules","@unbrained"),i=X.join(n,"pm-cli");await ie.mkdir(n,{recursive:!0}),await ie.rm(i,{recursive:!0,force:!0}),await ie.symlink(t,i,process.platform==="win32"?"junction":"dir")},vi=async e=>{let t=X.resolve(e),n=X.dirname(t),i=X.parse(n).root,r=await ie.realpath(i).catch(()=>i),a=X.relative(i,n),o=a===""?[]:a.split(X.sep);for(let[s,c]of o.entries()){let d=X.join(r,c);try{r=await ie.realpath(d)}catch{r=X.join(r,...o.slice(s));break}}return X.join(r,X.basename(t))},Pp=async(e,t,n,i=ak.tmpdir())=>Pt("extension_install_copy",async()=>{let r=X.resolve(e),a=await ie.realpath(r).catch(()=>r),o=await vi(t);if(a===o)return;if(!me(a,o)){await n(a,t,{recursive:!0,force:!0,filter:u=>wi(a,o,X.resolve(u),!1)});return}let s=await ie.realpath(X.resolve(i)).catch(()=>vi(i)),c=me(a,s)?X.dirname(a):s;if(me(a,c))throw new g(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,y.USAGE,{code:"extension_install_source_contains_destination"});let d=await ie.mkdtemp(X.join(c,"pm-extension-copy-")),l=X.join(d,"extension");try{await n(a,l,{recursive:!0,force:!0,filter:u=>wi(a,o,X.resolve(u),!0)}),await n(l,t,{recursive:!0,force:!0})}finally{await ie.rm(d,{recursive:!0,force:!0})}}),Lp=async(e,t,n=ie.cp)=>{for(let i=1;i<=Rp;i+=1)try{await Pt("extension_install_copy",async()=>{await ie.rm(t,{recursive:!0,force:!0}),await Pp(e,t,n)});return}catch(r){if(!Tp(r)||i===Rp)throw r;await $p(Ap)}},es=async e=>{let t;try{t=await ie.readFile(X.join(e,"owner.json"),"utf8")}catch(r){if(!yt(r))throw r;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let i=n.token;return typeof i=="string"&&i.length>0?i:null},Np=async(e,t)=>await es(e)!==t?!1:(await ie.rm(e,{recursive:!0,force:!0}),!0),dk=async(e,t)=>{let n;try{n=await ie.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let i=await es(e);return i===null?(await ie.rm(e,{recursive:!0,force:!0}),!0):Np(e,i)},lk=(e,t,n)=>{let i=Promise.resolve(),r=setInterval(()=>{i=i.then(async()=>{if(await es(e)!==t)return;let a=new Date;await ie.utimes(e,a,a)}).catch(()=>{})},n);return r.unref(),async()=>{clearInterval(r),await i}},uk=async(e,t)=>{await ie.mkdir(e);try{await ie.writeFile(X.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
45
|
+
`,"utf8")}catch(n){throw await ie.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},mk=async(e,t,n,i,r)=>{for(let a=1;a<=n;a+=1)try{return await uk(e,t),!0}catch(o){if(!Br(o,"EEXIST"))throw o;await dk(e,r)?a-=1:await $p(i)}return!1},ts=async(e,t,n,i)=>Pt("extension_install",async()=>{let r=X.join(e,"runtime","extension-install-locks"),a=X.join(r,"scope.lock");await ie.mkdir(r,{recursive:!0});let{attempts:o=ok,delay_ms:s=Ap,stale_ms:c=sk,heartbeat_ms:d}=i??{};if(![o,s,c,d].filter(w=>w!==void 0).every(Number.isFinite))throw new g("Extension install lock timings must be finite numbers.",y.USAGE);let l=Math.max(1,Math.floor(o)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(d??m/3);if(m<=0||f<=0||f>=m)throw new g("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",y.USAGE);let p={pid:process.pid,token:rk(),created_at:$(),destination:t};if(!await mk(a,p,l,u,m))throw new g(`Timed out waiting for extension install lock for "${t}".`,y.CONFLICT);let h=lk(a,p.token,f),_=!1;try{let w=await n();return _=!0,w}finally{await h(),await Np(a,p.token).catch(w=>{if(_)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var ns=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o])}});return await Promise.all(a),i};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function Mp(e,t){let n=R(e),i=t.find(r=>R(r.name)===n);return{command_paths:[...i?.command_paths??[]].sort((r,a)=>r.localeCompare(a)),action_paths:[...i?.action_paths??[]].sort((r,a)=>r.localeCompare(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]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function jp(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${R(a.name)}`]:[])),i=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>a.passThrough!==!0).filter(a=>!n.has(`${a.layer}:${R(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),r=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...i,...r])].sort((a,o)=>a.localeCompare(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]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var Fp=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Yi(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,i)=>i.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));import{execFile as pk}from"node:child_process";import{promisify as fk}from"node:util";import hk from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();var _k=fk(pk),Hp=1e4;function Up(e,t,n){if(typeof t=="string")try{let i=hk.resolve(e,t);if(i.type==="version")return i.fetchSpec}catch{}throw new Error(n)}async function gk(e,t){try{return(await _k(Vo(),e,{encoding:"utf8",timeout:t,maxBuffer:65536,shell:Ko(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function zp(e,t=gk){let n=$();try{if(e.kind!=="npm"||!e.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(e.package))throw new Error("missing_or_invalid_npm_package_identity");let i=Up(e.package,e.version,"missing_or_invalid_installed_npm_version"),r=await t(["view",e.package,"dist-tags.latest","--json","--ignore-scripts"],Hp),a;try{a=JSON.parse(r)}catch{throw new Error("invalid_npm_registry_metadata")}let o=Array.isArray(a)&&a.length===1?a[0]:a,s=Up(e.package,o,"invalid_npm_registry_version");return{checked_at:n,available:s!==i,remote_version:s}}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(i)}}}var yk=(e,t,n)=>{let i=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),r=i.find(o=>o.ref.endsWith("^{}"))??i[0];if(!r)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:r.commit,available:r.commit!==a}:{checked_at:n,remote_commit:r.commit,available:null,error:"missing_installed_commit"}},is=async(e,t=Ur)=>{let n=$();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let i=[e.ref?.trim(),"HEAD"].find(Boolean),r=await t(["ls-remote",e.repository,i,`${i}^{}`],void 0,Hp);return yk(r,e.commit,n)}catch(i){return{checked_at:n,available:null,error:i instanceof Error?i.message:String(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]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();var wk=4;async function Wp(e,t=!1){let n=await ns(e.entries,wk,async i=>{if(!["github","npm"].includes(i.source.kind))return i;if(t)return{...i,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};let r=i.source.kind==="github"?await is(i.source):await zp(i.source);return{...i,last_update_check_at:r.checked_at,last_update_remote_commit:"remote_commit"in r?r.remote_commit:void 0,last_update_remote_version:"remote_version"in r?r.remote_version:void 0,update_available:r.available,update_error:r.error}});return{...e,entries:ui(n)}}import vk from"node:fs/promises";import bk 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]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function rs(e){return bk.join(e,"extension-migrations.json")}function qp(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Gp(e,t){return`${e.layer}:${e.name}:${t}`}async function kk(e){let t=rs(e);if(!await D(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await vk.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(i=>typeof i?.key=="string"&&(i.status==="applied"||i.status==="failed")):[]}}async function as(e,t){let n=await kk(e),i=new Map(n.entries.map(r=>[r.key,r]));return t.forEach((r,a)=>{let o=qp(r,a),s=i.get(Gp(r,o));s&&(r.definition.status=s.status,s.status==="failed"?r.definition.reason=s.error:(delete r.definition.reason,delete r.definition.error,delete r.definition.message))}),n}async function Ek(e){let t=await as(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),i=[],r=!1,a=e.migrations.map((l,u)=>({migration:l,index:u})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:u}of a){let m=qp(l,u),f=Gp(l,m),p=n.get(f),h=String(l.definition.status??"pending").toLowerCase(),_=p?.status??(h==="applied"||h==="failed"?h:"pending");if(_==="applied"){i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"skipped"});continue}if(e.dryRun===!0){i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:_}));let E={key:f,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(f,E),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"applied"}),r=!0}catch(E){let k=E instanceof Error?E.message:String(E),I={key:f,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:k};n.set(f,I),l.definition.status="failed",l.definition.reason=k,i.push({key:f,layer:l.layer,extension:l.name,id:m,before:_,outcome:"failed",error:k}),r=!0}}if(r){let l=await T(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await on({pmRoot:e.pmRoot,filePath:rs(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
|
|
46
|
+
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let o=i.filter(l=>l.outcome==="pending").length,s=i.filter(l=>l.outcome==="applied").length,c=i.filter(l=>l.outcome==="skipped").length,d=i.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:rs(e.pmRoot),total:i.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:d,migrations:i}}async function Bp(e){let t=await T(e.resolvedRoots.settings_root),n=await Je({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Ve(n);e.warnings.push(...n.warnings,...i.warnings);let r=await Ek({pmRoot:e.resolvedRoots.pm_root,migrations:i.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:r,load_failure_count:n.failed.length,activation_failure_count:i.failed.length},r.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17cca82e-e9f9-5633-8d91-bc6c2b560d5f")}catch{}})();function Jp(e,t){let n=e.filter(i=>i.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:i,result:r})=>{let a=r.details;return{alias:i,ok:r.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,previous_state_preserved:a.previous_state_preserved,rollback:a.rollback,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:r.warnings}})}}import Vr from"node:fs/promises";import Jr 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]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var Sk=new Set(["node_modules",".git","dist","build","coverage"]);async function Vp(e,t,n,i){let r=e.source.kind==="local"?await Vr.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?r.isDirectory()?"directory":"archive":e.source.kind,o=await xk(e.directory,t,i),s={source_mode:a,...a==="archive"?{archive_bytes:r.size}:{},copy:o},c=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await D(Jr.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let d=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new g(`Local extension source scan stopped at ${d}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,y.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function xk(e,t,n={}){let{maxEntries:i=1e4,maxDepth:r=64,signal:a}=n;if(![i,r].every(u=>Number.isSafeInteger(u)&&u>0))throw new g("maxEntries and maxDepth must be positive safe integers.",y.USAGE);a?.throwIfAborted();let o=await Vr.realpath(e),s=await vi(t),c=await Sn(o,s);a?.throwIfAborted();let d=c?"in_place":me(o,s)?"nested_filtered_snapshot":"directory_snapshot",l={copy_scope:d,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:i,max_depth:r};return d==="in_place"||await Kp(o,0,l,a),l}async function Kp(e,t,n,i){i?.throwIfAborted();let r=await Vr.opendir(e);for await(let a of r){if(i?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=Jr.join(e,a.name);if(!wi(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(Jr.relative(n.source_directory,o).split(Jr.sep).some(s=>Sk.has(s))&&(n.development_entries+=1),await Ik(o,t,n,i),!n.complete)return}}async function Ik(e,t,n,i){let r=await Vr.lstat(e);if(i?.throwIfAborted(),r.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Kp(e,t+1,n,i)}else r.isFile()?(n.files+=1,n.bytes+=r.size):r.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import Rk from"node:fs/promises";import Ak 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]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function Ck(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function Tk(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function os(e){let t=Ak.join(e,"manifest.json"),n;try{n=await Rk.readFile(t,"utf8")}catch(s){if(yt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let i;try{i=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof i!="object"||i===null||Array.isArray(i))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let r=i,a=$c(r),o=Ck(r);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>Tk(o,s)),remediation:a.findings.map(s=>s.message)}}function Yp(e){return os(Be(e))}import $k from"node:fs/promises";import Dk from"npm-package-arg";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bef4424-f5b8-511b-91f7-0b39cf11f515")}catch{}})();async function Ok(e,t){if(e.kind!=="local"||e.input.startsWith(".")||e.input.includes("\\")||e.input.includes("/")&&!/^@[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/u.test(e.input))return e;try{return await $k.lstat(e.absolute_path),e}catch(a){if(!j(a))throw a}let n=e.input.trim(),i=t.filter(a=>a.source.kind==="npm"),r=(i.find(a=>a.name===n)??i.find(a=>a.directory===n)??i.find(a=>a.source.package===n))?.source.package;if(r===void 0)return e;try{let a=Dk(r);if(!a.registry||a.name!==r)return e}catch{return e}return fi(`npm:${r}`,{})}async function Xp(e,t,n,i=[]){let r=typeof t=="string"?null:await pi(e),a=r===null?null:e.trim().toLowerCase(),o=a===null?null:await Wm(a),s=await Ok(fi(r??e,{forceGithub:typeof t=="string",ref:n}),i),c=a===null?null:await Vm(e);return{bundledAliasName:a,bundledPackageName:o,installSource:s,sourceResolution:{requested:e,selected:{kind:a===null?s.kind:"builtin",input:a??s.input,...o===null?{}:{package:o}},ambiguous:c!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...a===null?[]:[{kind:"builtin",input:a,...o===null?{}:{package:o},command:`pm install ${a}`}],...c===null?[]:[{kind:"npm",input:`npm:${c.package}`,package:c.package,...c.version===void 0?{}:{version:c.version},directory:c.directory,command:`pm install npm:${c.package}`}]]}}}import He from"node:fs/promises";import xn 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]="7c06c702-29ea-5552-aadc-52dfc9c238ef")}catch{}})();var ss=async e=>He.readFile(e).catch(t=>{if(Br(t,"ENOENT"))return null;throw t}),Pk=async(e,t,n,i,r)=>Pt("extension_install_backup",async()=>{let a=li(e),o=Bt(t),[s,c]=await Promise.all([ss(a),ss(o)]);return i&&await He.cp(n,r,{recursive:!0,force:!0}),{backupDirectory:r,destinationDirectory:n,destinationExists:i,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}}),Zp=async e=>Pt("extension_install_rollback",async()=>{await He.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await He.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])if(n===null)await He.rm(t,{force:!0});else if(t===e.settingsPath){let i=xn.dirname(e.settingsPath),r=await T(i);try{await on({pmRoot:i,filePath:t,raw:n.toString("utf8"),op:"extension:install:rollback",author:z(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms})}finally{Qd(i)}}else await He.mkdir(xn.dirname(t),{recursive:!0}),await He.writeFile(t,n)});async function Qp(e,t){let n=await D(e.destinationDirectory),i=await Sn(e.sourceDirectory,e.destinationDirectory);await He.mkdir(e.selectedRoot,{recursive:!0});let r=xn.join(xn.dirname(e.selectedRoot),"runtime","extension-installs");await He.mkdir(r,{recursive:!0});let a=await He.mkdtemp(xn.join(r,".pm-extension-install-backup-")),o=xn.join(a,"destination"),s=["package","install",o,`--${e.scope}`],c=le(s),d=!1;try{let l=await Pk(e.selectedRoot,e.settingsRoot,e.destinationDirectory,n,o),u;try{u=await t()}catch(m){try{await Zp(l)}catch(f){d=!0;let p=new g(`Extension install failed: ${String(m)}; rollback failed: ${String(f)}`,y.GENERIC_FAILURE,{code:"extension_install_rollback_failed",original_code:m instanceof g?m.code:void 0,required:"Restore the previous package before retrying the replacement. Previous state was not preserved.",nextSteps:[n?c:"Repair the reported metadata write failure, then retry the original install."],...n?{recovery:{suggested_retry:c,suggested_retry_args:s}}:{}});throw Object.defineProperty(p,"cause",{value:m,configurable:!0,writable:!0}),p}throw m}if(u.ok)return u;if(!n||i)return{...u,details:{...u.details,previous_state_preserved:!1}};try{await Zp(l)}catch(m){return d=!0,{...u,details:{...u.details,previous_state_preserved:!1,rollback:{status:"failed",error:String(m),backup_directory:o,recovery_command:c,recovery_args:s}}}}return{...u,details:{...u.details,overwritten:!1,settings_changed:!1,previous_state_preserved:!0,rollback:{status:"restored"}}}}finally{d||await He.rm(a,{recursive:!0,force:!0}).catch(()=>{})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ae11424-9de8-5bce-91b4-e8901459fb5f")}catch{}})();var rf=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],Lk=rf.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),Nk={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},Mk="__pm_native_output",jk=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],af=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Fk=["disabled","require_trusted","require_provenance"],of={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},Uk=e=>{let t=e??of,n={};for(let i of jk)n[i]=Ce(t[i]??[]);return n},Hk=(e,t)=>{for(let n of af)t[n].length>0&&(e[n]=t[n]);return e},zk=(e,t)=>{for(let n of Fk)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},Wk=e=>{let t={};for(let n of af)t[n]=Ce(e[n]??[]);return t},qk=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:Hk(zk({name:t},e),Wk(e))},Gk=e=>(e??[]).map(t=>qk(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),Bk=e=>{let t=Object.assign({},of,e??{}),n=Uk(e),i=Gk(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:i}},sf=async(e,t)=>{let n=[t],i=await qm(t);i&&n.push(i);let r=[...new Set(n.map(a=>R(a)).filter(a=>a.length>0))];for(let a of r){let o=e.find(c=>R(c.name)===a);if(o)return o;let s=e.find(c=>R(c.directory)===a);if(s)return s}},cf=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled));return new Set(Ce(e.extensions.disabled)).has(n)?!1:i.size===0?!0:i.has(n)},df=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled)),r=new Set(Ce(e.extensions.disabled)),a=[...i],o=[...r];return r.delete(n),i.size>0&&i.add(n),e.extensions.enabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Jk=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled)),r=new Set(Ce(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.add(n),e.extensions.enabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Vk=(e,t)=>{let n=t.trim(),i=new Set(Ce(e.extensions.enabled)),r=new Set(Ce(e.extensions.disabled)),a=[...i],o=[...r];return i.delete(n),r.delete(n),e.extensions.enabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},Kk=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),i=rf.map(([r,a,o])=>({action:a,flag:o,distance:Ec(t,r,n)})).filter(r=>r.distance!==null).sort((r,a)=>r.distance-a.distance)[0];return i?{action:i.action,flag:i.flag}:null},Yk=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=Kk(e);if(!i)return new g(`One action flag is required. Use one of: ${Lk}. Bare \`pm package\` and \`pm extension\` default to --explore.`,y.USAGE);let r=`pm ${n} ${i.flag}`;return Zi({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(lf),retry_command:r,message_suffix:`. Did you mean "${i.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:r,reason:`nearest lifecycle action for "${e}"`}]})},Xk=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],lf={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},Zk=e=>lf[e]??null,Qk=(e,t)=>{let n=[...new Set(Xk.filter(([i])=>t[i]===!0).map(([,i])=>i))];if(n.length===0){if(e===void 0)return"explore";let i=Zk(e.trim().toLowerCase());if(i)return i;throw Yk(e,t)}if(n.length>1)throw new g("Extension action flags are mutually exclusive.",y.USAGE);return n[0]},eE=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new g('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"},tE=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&!["github","npm"].includes(e.source.kind)?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],uf=e=>{for(let t of tE){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},mf=(e,t,n,i)=>{let r=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:r.contributions,managed:!!n,source:r.source,update_available:r.update_available,last_update_check_at:r.last_update_check_at,last_update_remote_commit:r.last_update_remote_commit,last_update_remote_version:r.last_update_remote_version,update_error:r.update_error,update_check_status:i.status,update_check_reason:i.reason}},nE=(e,t,n,i)=>{let r=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},i),a=i?cf(n,i.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:mf({name:r.name,directory:e,version:r.manifest_version,entry:r.manifest_entry,enabled:a},t,i,uf(i))}},iE=async(e,t,n,i,r,a)=>{let o=Oe.join(e,t),s=Oe.join(o,"manifest.json"),c=a.get(R(t));if(!await D(s))return nE(t,n,i,c);let d=Symbol("invalid-extension-manifest-json"),l=await In.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>d);if(l===d)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=Uo(l);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=r.get(R(u.name))??a.get(R(t));return{summary:mf({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:cf(i,u.name)},n,m,uf(m))}},et=async(e,t,n,i)=>{if(!await D(e))return{extensions:[],warnings:[]};let r=(await In.readdir(e,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort((d,l)=>d.localeCompare(l)),a=new Map(i.entries.map(d=>[R(d.name),d])),o=new Map(i.entries.map(d=>[R(d.directory),d])),s=[],c=[];for(let d of r){let l=await iE(e,d,t,n,a,o);l.warning&&s.push(l.warning),l.summary&&c.push(l.summary)}return{extensions:c.sort((d,l)=>d.name.localeCompare(l.name)),warnings:s.sort((d,l)=>d.localeCompare(l))}},rE=ld(),aE=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,oE=(e,t,n,i)=>{let r=n.command_paths.map(s=>`pm ${s} --help`),a=i?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...r]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:aE(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:r,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},sE=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},pf=e=>e.map(t=>sE(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),ff=(e,t,n)=>{let i=R(e);return t.find(r=>(n===void 0||r.layer===n)&&R(r.name)===i)},cE=(e,t,n,i)=>n.find(r=>r.scope===t&&R(r.name)===R(e))?.activation_status??(i?"failed":"unknown"),hf=(e,t,n,i,r)=>rE.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await In.mkdtemp(Oe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ge(import.meta.url,["../.."]);try{let s=await Je({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:r.noExtensions===!0,reload_token:Ma(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Ve({...s}),d=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...pf(c.failed)],l=Object.fromEntries(s.loaded.map(u=>[R(u.name),Jc(gn(c,{extensionName:u.name}))]));return{installed:qr(i,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:d,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:l}}finally{await In.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),ds=async(e,t,n,i)=>{let r=n.filter(c=>!c.managed),a=[...r].sort((c,d)=>{let l=c.name.localeCompare(d.name);return l!==0?l:c.directory.localeCompare(d.directory)}),o=i,s=[];for(let c of a){let d=Oe.join(e,c.directory),l=await kn(d),u=$(),m={kind:"local",input:c.name,location:d};o=mi(o,{name:l.manifest.name,directory:c.directory,scope:t,manifest_version:l.manifest.version,manifest_entry:l.manifest.entry,capabilities:[...l.manifest.capabilities],contributions:l.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:l.manifest.name,directory:c.directory,version:l.manifest.version,entry:l.manifest.entry,source:m})}return s.length>0&&await En(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-r.length}},dE=(e,t)=>{let n=M(process.cwd(),t.path),i=Jt(n,process.cwd()),r=e==="global"?Ui(process.cwd()):n,a=e==="global"?i.global:i.project;return{pm_root:n,scope:e,settings_root:r,selected_root:a,roots:i}},Kr=e=>{let t=[e.gh,e.github].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new g('Options "--gh" and "--github" must match when both are provided.',y.USAGE);return n[0]},lE=e=>Nk[e],uE=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",i=e==="install"?"source":"name",r=`${n} ${i}`,a=lE(e),o=`<${i}>`,s=`pm ${n} ${a} ${o}`;throw new g(`Action "${e}" requires ${r} input.`,y.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${i} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${i} target`}]}})},Yr=(e,t,n={})=>{let i=e?.trim();if(i)return i;if(t==="init")throw new g('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',y.USAGE);return uE(t,n)},mE=(e,t)=>{let n=new Set([...t.registrations.item_types.map(i=>({entry:i,count:i.types.length})),...t.registrations.item_fields.map(i=>({entry:i,count:i.fields.length}))].filter(({count:i})=>i>0).map(({entry:i})=>`${i.layer}:${R(i.name)}`));return e.loaded.filter(i=>(i.activation?.commands??[]).length>0).filter(i=>n.has(`${i.layer}:${R(i.name)}`)).map(i=>`extension_schema_narrow_activation:${i.layer}:${i.name}`).filter((i,r,a)=>a.indexOf(i)===r).sort((i,r)=>i.localeCompare(r))},pE=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(i=>i.triggered&&!i.allowed);if(n)throw new g(n.message,y.USAGE)},fE=(e,t,n)=>{let i=String(e??"").trim().toLowerCase(),r=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:r?[]:["init","scaffold"]}[t]??[]).includes(i)?void 0:e},hE=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},_E=(e,t,n)=>{let i={ok:n,action:e.action,scope:e.scope,roots:hE(e),warnings:[...new Set(e.warnings)].sort((r,a)=>r.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(i,Mk,{value:!0,enumerable:!1,configurable:!1}),i},ls=async(e,t,n)=>{let i=Qk(e,t);pE(i,t);let r=fE(e,i,t),a=eE(t),o=dE(a,n),s={action:i,normalizedTarget:r,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},c={...s,withResult:(d,l=!0)=>_E(s,d,l)};return await KE(c)},gE=(e,t)=>{let n=t.vocabulary??"extension",i=e.target_path.replace(/\\/g,"/"),r=_d(i),a={package:`Install dependencies: cd ${r}, then run "npm install"`,extension:`Install type-check dependencies: cd ${r}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${r}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${r}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[a[n],...s,`Install the scaffold: ${le(n==="package"?["install","--project",i]:["extension","--install","--project",i])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},yE=async e=>{let{action:t,normalizedTarget:n,options:i,withResult:r}=e;if([Kr(i),i.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new g('Action "init" does not accept --gh/--github/--ref options.',y.USAGE);let a=Yr(n,t,i),o=await mp(a,i.vocabulary??"extension",i.capability,i.declarative===!0);return r({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:gE(o,i)})},wE=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:i,options:r,global:a,withResult:o}=e;if(t!==void 0)throw new g('Action "reload" does not accept a target argument.',y.USAGE);let s=await T(n.settings_root),c=Ma(),d=await Je({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:c,cache_bust:!0});i.push(...d.warnings);let l=await Ve(d);i.push(...l.warnings);let u={reload:{token:c,cache_bust:!0,watch:r.watch===!0},loaded_count:d.loaded.length,failed_count:d.failed.length,activated_count:Math.max(0,d.loaded.length-l.failed.length),activation_failed_count:l.failed.length,loaded_extensions:d.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return r.watch===!0&&i.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(u)},vE=async e=>{let{normalizedTarget:t,scope:n,options:i,global:r,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new g('Action "catalog" does not accept a package target.',y.USAGE);return a(await Gm(n,r,i))},bE=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),kE=e=>({kind:"local",input:e.input,location:e.absolute_path}),EE=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),SE=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),xE=(e,t,n,i)=>e?bE(e,t):n.kind==="local"?kE(n):n.kind==="npm"?EE(n,i):SE(n,i),IE=(e,t,n,i)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:i}:jm(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:i}:{installed_at:i,updated_at:i},RE=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r}=e,{validated:a,destinationDirectoryName:o}=t,s=await T(i.settings_root),c=await he(i.selected_root);r.push(...c.warnings);let d=Oe.join(i.selected_root,o),l=await D(d),u=await Sn(a.directory,d);await In.mkdir(i.selected_root,{recursive:!0});let m=xE(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),f=c.state.entries.find(w=>R(w.name)===R(a.manifest.name)),p=IE(f,a.manifest.version,m,$()),h=mi(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...p,source:m}),_=df(s,a.manifest.name);return u||await Lp(a.directory,d),await Dp(d),await Op(d),await En(i.selected_root,h),_&&await lr(i.settings_root,s,"settings:write"),{settings:s,managedState:h,sourceRecord:m,destinationDirectory:d,destinationExists:l,installInPlace:u,activationChanged:_}},AE=async(e,t,n)=>{let i=n.filter(r=>R(r.name)===R(t)).flatMap(r=>r.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&i.length>0&&await ci(e.resolvedRoots.pm_root,i,e.warnings,"install:type-folder"),i},CE=(e,t,n,i,r)=>{let a=ff(t,n.activation_failures,e.scope),o=cE(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:i.command_paths,registered_actions:i.action_paths,registered_item_types:r,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},TE=async(e,t)=>{let{scope:n,resolvedRoots:i,warnings:r,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t;return Qp({selectedRoot:i.selected_root,settingsRoot:i.settings_root,destinationDirectory:Oe.join(i.selected_root,c),sourceDirectory:s.directory,scope:n},async()=>{let d=await RE(e,t),l=await et(i.selected_root,n,d.settings,d.managedState);r.push(...l.warnings);let u=await hf(i.pm_root,Oe.dirname(i.selected_root),d.settings,l.extensions,a);r.push(...u.warnings);let m=await AE(e,s.manifest.name,u.item_type_registrations),f=Mp(s.manifest.name,u.installed),p=CE(e,s.manifest.name,u,f,m),h=u.contribution_inventories[R(s.manifest.name)];return h&&(d.managedState=await Fm(i.selected_root,d.managedState,s.manifest.name,h)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:d.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:d.destinationDirectory,overwritten:[d.destinationExists,!d.installInPlace].every(Boolean),installed_in_place:d.installInPlace,activated:p.activated,settings_changed:d.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:oE(s.manifest.name,d.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)})},$E=async e=>{let{options:t,global:n,warnings:i,withResult:r}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new g('Action "install all" does not accept --ref.',y.USAGE);let a=[],o=new Map;for(let s of await Fr()){let c=await pi(s),d=Oe.resolve(c),l=o.get(d);l===void 0&&(l=await ls(s,{...t,install:!0},n),o.set(d,l)),a.push({alias:s,result:l})}return i.push(...a.flatMap(s=>s.result.warnings)),r(Jp(a,t.dryRun===!0),a.every(s=>s.result.ok))},DE=async(e,t,n)=>{let{resolvedRoots:i}=e,{bundledAliasName:r,bundledPackageName:a,installSource:o,sourceResolution:s}=await Xp(t,n,e.options.ref,(await he(i.selected_root)).state.entries);if(s.ambiguous){let d=s.candidates.find(l=>l.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${r}:npm:${d.package}`)}let c=await ep(o);try{let d=await kn(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),l=Mr(d.manifest.name),u=e.options.dryRun===!0||o.kind==="local"&&r===null?await Vp(c,Oe.join(i.selected_root,l),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:d.manifest.name,version:d.manifest.version},source_resolution:s,install_plan:u}):await ts(i.settings_root,l,()=>TE(e,{validated:d,destinationDirectoryName:l,bundledAliasName:r,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},OE=async e=>{let t=Kr(e.options),n=t??Yr(e.normalizedTarget,e.action,e.options);return[t===void 0,Hm(n)].every(Boolean)?$E(e):DE(e,n,t)},PE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e;if(t!==void 0)throw new g('Action "adopt-all" does not accept a target argument.',y.USAGE);if(Kr(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new g('Action "adopt-all" does not accept --gh/--github/--ref options.',y.USAGE);let s=await T(i.settings_root),c=await he(i.selected_root);r.push(...c.warnings);let d=await et(i.selected_root,n,s,c.state);r.push(...d.warnings);let l=await ds(i.selected_root,n,d.extensions,c.state),u=await et(i.selected_root,n,s,l.state);r.push(...u.warnings);let m=Gr(n,r,u.extensions,a);r.push(...m.warnings);let f=new Map(u.extensions.map(_=>[`${R(_.name)}:${R(_.directory)}`,_])),p=new Map(u.extensions.map(_=>[R(_.directory),_])),h=l.adopted_entries.map(_=>{let w=R(_.directory),v=f.get(`${R(_.name)}:${w}`)??p.get(w);return{..._,..._f(v)}});return o({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:l.already_managed_count,extensions:h,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},_f=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),LE=(e,t,n,i)=>{if(e===void 0)return{kind:"local",input:t,location:n};let r=fi(e,{forceGithub:!0,ref:i});if(r.kind!=="github")throw new g(`Invalid GitHub shorthand "${e}".`,y.USAGE);return{kind:"github",input:r.input,location:r.subpath??".",repository:r.repository,owner:r.owner,repo:r.repo,ref:r.ref,subpath:r.subpath}},NE=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o,withResult:s}=e,c=Yr(n,t,o),d=Kr(o),l=await T(r.settings_root),u=await he(r.selected_root);a.push(...u.warnings);let m=await et(r.selected_root,i,l,u.state);a.push(...m.warnings);let f=await sf(m.extensions,c);if(!f)throw new g(`Installed extension "${c}" was not found in ${i} scope.`,y.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Oe.join(r.selected_root,f.directory),h=await kn(p),_=$(),w=LE(d,c,p,o.ref),v=mi(u.state,{name:h.manifest.name,directory:f.directory,scope:i,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:_,updated_at:_,source:w});await En(r.selected_root,v);let E=await et(r.selected_root,i,l,v);a.push(...E.warnings);let k=E.extensions.find(I=>R(I.name)===R(h.manifest.name))??E.extensions.find(I=>R(I.directory)===R(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,..._f(k)})},gf=async e=>{let{action:t,normalizedTarget:n,scope:i,resolvedRoots:r,warnings:a,options:o}=e,s=Yr(n,t,o),c=await T(r.settings_root),d=await he(r.selected_root);a.push(...d.warnings);let l=await et(r.selected_root,i,c,d.state);a.push(...l.warnings);let u=await sf(l.extensions,s);if(!u)throw new g(`Installed extension "${s}" was not found in ${i} scope.`,y.NOT_FOUND);return{settings:c,managedStateRead:d,candidate:u}},ME=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:i,managedStateRead:r,candidate:a}=await gf(e),o=Oe.join(t.selected_root,a.directory);await In.rm(o,{recursive:!0,force:!0});let s={...r.state,updated_at:$(),entries:r.state.entries.filter(d=>R(d.name)!==R(a.name)&&R(d.directory)!==R(a.directory))};await En(t.selected_root,s);let c=Vk(i,a.name);return c&&await lr(t.settings_root,i,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},ef=async e=>{let{action:t,resolvedRoots:n,warnings:i,global:r,withResult:a}=e,{settings:o,candidate:s}=await gf(e),c=t==="activate"?df(o,s.name):Jk(o,s.name);c&&await lr(n.settings_root,o,"settings:write");let d=t==="activate"?await hf(n.pm_root,Oe.dirname(n.selected_root),o,[s],r).then(l=>(i.push(...l.warnings),ff(s.name,l.activation_failures,e.scope))):void 0;return d&&i.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&d===void 0,runtime_active:t==="activate"&&d===void 0,activation_failure:d??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},d===void 0)},jE=(e,t,n,i,r,a)=>{let o=i==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=r?.adopted_entries.length??0,d=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...d.filter(([l])=>l).map(([,l])=>l)].map(l=>l.trim()).filter(l=>l.length>0))]},cs=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),FE=(e,t,n,i)=>{if(e!=="project"||t||!cs(i))return null;let r=n==="package"?"package":"extension";return`Global ${r} registrations are included in project diagnostics. For hermetic ${r} smoke tests, rerun pm ${r} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},UE=(e,t,n)=>{if(String(e??"").trim().length>0)throw new g('Action "doctor" does not accept a target argument.',y.USAGE);let i=[n.isolated,n.ignoreGlobal].includes(!0);if([i,t==="global"].every(Boolean))throw new g("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",y.USAGE);let r=Ep(n.detail),a=n.trace===!0;if([a,r!=="deep"].every(Boolean))throw new g("--trace requires --detail deep with --doctor.",y.USAGE);return{isolated:i,detailMode:r,includeTrace:a}},HE=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let i=await ds(e.resolvedRoots.selected_root,e.scope,t,n);return{state:i.state,fix:i}},zE=(e,t,n,i)=>{let r=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:cs(i),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${r} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:cs(i),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${r} doctor --project --detail deep --trace`}},WE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:d,includeTrace:l}=UE(t,n,a),u=await T(i.settings_root),m=await he(i.selected_root);r.push(...m.warnings);let f=await et(i.selected_root,n,u,m.state);r.push(...f.warnings);let{state:p,fix:h}=await HE(e,f.extensions,m.state),_=await et(i.selected_root,n,u,p);r.push(..._.warnings);let w=await Je({pmRoot:i.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Ve({...w,loaded:w.loaded}),E=await Yp(i.pm_root);r.push(...E.warnings,...w.warnings),r.push(...vp(w.failed)),r.push(...v.warnings),r.push(...bp(v.failed)),r.push(...kp(w,v)),r.push(...jp(v,w)),r.push(...mE(w,v)),r.push(...Fp(v));let k=qr(_.extensions,w,v),I=xp(n,k,w.loaded.map(U=>({layer:U.layer,name:U.name})),w.failed.map(U=>({name:U.name})),w.disabled_by_flag);r.push(...I.warnings);let C=k.filter(U=>U.update_check_status==="failed").map(U=>`extension_update_check_failed:${U.name}`);r.push(...C);let S=Gr(n,r,k,a);r.push(...S.warnings);let b=[...S.warnings],O={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},P=gi(b),x=yi(),q=S.warning_codes,Se=FE(n,c,a.vocabulary,w),_e=jE(S.remediation,w.failed.length,v.failed.length,a.vocabulary,h,Se),pe=zE(n,c,a.vocabulary,w),Le={status:S.status,scope:n,warning_count:S.warning_count,warning_codes:q,total_extensions:k.length,managed_total:k.filter(U=>U.managed).length,enabled_total:k.filter(U=>U.enabled).length,active_total:k.filter(U=>U.active).length,unmanaged_loaded_extension_count:S.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:S.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:S.unmanaged_expected_extension_count,runtime_active_total:k.filter(U=>U.runtime_active===!0).length,activation_status_totals:{ok:k.filter(U=>U.activation_status==="ok").length,failed:k.filter(U=>U.activation_status==="failed").length,not_loaded:k.filter(U=>U.activation_status==="not_loaded").length,unknown:k.filter(U=>U.activation_status==="unknown").length},unknown_capability_count:P.length,capability_contract_version:x.version,update_available_total:S.update_available_total,update_check_status_totals:S.update_check_status_totals,update_health_coverage:S.update_health_coverage,update_health_partial:S.update_health_partial,update_check_failed_total:k.filter(U=>U.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:Zo(w.failed),activation_failures:Zo(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:I.warnings.length,trace_enabled:l,isolation:pe,policy:O,remediation:_e},Pi=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(U=>U.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:_.extensions.filter(U=>U.managed).length,adopted_extensions:[]},jn={mode:d,summary:Le,triage:S,trace_enabled:l,capability_contract:x,capability_guidance:P,managed_state_fix:Pi,author_manifest:E,isolation:pe,policy:w.policy};if(d==="deep"){let U=l?v.failed:v.failed.map(G=>{let{trace:Li,...Ni}=G;return Ni});jn.deep={warnings:b,warning_codes:q,capability_contract:x,capability_guidance:P,trace_enabled:l,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:k,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(G=>({layer:G.layer,directory:G.directory,name:G.name,version:G.version,entry:G.entry,priority:G.priority}))},activation:{failed:U,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:I.summary},l&&(jn.deep.trace={activation_failures:v.failed.filter(G=>G.trace!==void 0).map(G=>({layer:G.layer,name:G.name,entry_path:G.entry_path,error:G.error,method:G.trace.method,command:G.trace.command,capability:G.trace.capability,missing_capability:G.trace.missing_capability,registration_index:G.trace.registration_index,expected_schema:G.trace.expected_schema,hint:G.trace.hint,received:G.trace.received}))})}return s(jn)},qE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:i,warnings:r,options:a,global:o,withResult:s}=e,c=await T(i.settings_root),d=await Je({pmRoot:i.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),l=await Ve(d);r.push(...d.warnings),r.push(...l.warnings);let u=fp(t,d,l);if(t!==void 0&&u.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",f=[...new Set(d.loaded.map(h=>a.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,_)=>h.localeCompare(_)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new g(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,y.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},GE=async(e,t,n)=>{let i=n,r=null;return[e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(r=await ds(e.resolvedRoots.selected_root,e.scope,t,n),i=r.state),e.action==="manage"&&(i=await Wp(i,e.options.offline)),{state:i,fix:r}},BE=async(e,t,n)=>{let i=await Je({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Ve({...i,loaded:i.loaded});return e.warnings.push(...i.warnings,...r.warnings),{installed:qr(n,i,r),failures:pf(r.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:i.failed.length,activation_failure_count:r.failed.length,warning_count:[...new Set([...i.warnings,...r.warnings])].length,policy:i.policy}}},JE=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},tf=async e=>{let{action:t,scope:n,resolvedRoots:i,warnings:r,options:a,withResult:o}=e,s=await T(i.settings_root),c=Bk(s.extensions.policy),d=await he(i.selected_root);r.push(...d.warnings);let l=await et(i.selected_root,n,s,d.state);r.push(...l.warnings);let{state:u,fix:m}=await GE(e,l.extensions,d.state),f=await et(i.selected_root,n,s,u);if(r.push(...f.warnings),t==="manage"&&a.offline===!0)for(let v of f.extensions)v.managed&&["npm","github"].includes(v.source.kind)&&(v.update_check_reason="offline_requested");if(t==="manage"){let v=f.extensions.filter(E=>E.update_check_status==="failed").map(E=>`extension_update_check_failed:${E.name}`);r.push(...v)}let p=await BE(e,s,f.extensions),h=p.installed,_=Gr(n,r,h,a);r.push(..._.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:_,policy:c};return p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=JE(m,h)),o(w)},nf={init:yE,install:OE,uninstall:ME,explore:tf,manage:tf,describe:qE,reload:wE,doctor:WE,catalog:vE,adopt:NE,"adopt-all":PE,activate:ef,deactivate:ef,migrate:Bp},VE=e=>[e.action==="uninstall",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[["doctor","manage"].includes(e.action),e.options.fixManagedState===!0].every(Boolean)].some(Boolean),KE=e=>VE(e)?ts(e.resolvedRoots.settings_root,`${e.action}-state`,()=>nf[e.action](e)):nf[e.action](e);import{execFile as YE}from"node:child_process";import{realpath as XE}from"node:fs/promises";import yf from"node:path";import{promisify as ZE}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 QE=ZE(YE),eS=32*1024*1024,tS=1e4,nS=["search/eval-queries.json"];function us(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function iS(e){return`'${e.replaceAll("'","'\\''")}'`}async function rS(e,t=XE){return t(e).catch(()=>yf.resolve(e))}async function Xr(e){let t=await St(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 rS(e),i=us(yf.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=Ll.map(a=>`${i}/${us(a)}`);try{let{stdout:a}=await QE("git",["ls-files","-z","--",...r.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:eS,windowsHide:!0,timeout:tS}),o=new Set(nS.map(d=>`${i}/${d}`)),s=[...new Set(a.split("\0").filter(d=>d.length>0&&!o.has(us(d))))].sort((d,l)=>d.localeCompare(l)),c=r.filter(d=>s.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(d=>iS(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import wf from"node:path";import{realpath as aS}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 vf(e,t){let n=t===null?[]:await jl(t,[wf.relative(t,wf.join(await aS(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function bf(e,t,n,i){if(t===null)return{audit:null,count:0,warnings:[]};let r=await ln(e,dn(n));if(r.status==="ok")return{audit:r,count:0,warnings:[]};let a=Math.max(1,r.missing_patterns.length+r.stale_patterns.length);return{audit:r,count:a,warnings:i?[`merge_fence_${r.status==="not_installed"?"missing":"drift"}:${a}`]:[]}}function kf(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}import{execFile as zS}from"node:child_process";import{randomUUID as WS}from"node:crypto";import{readdir as qS,realpath as Ct,stat as GS}from"node:fs/promises";import ae from"node:path";import{promisify as BS}from"node:util";import oS from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b3ef9db1-1d20-5d88-927e-a08edf563cd5")}catch{}})();function Ef(e,t,n){let i=qn(e,t);if(i.ok)return i.document;let r=structuredClone(e);for(let[a,o]of t.entries()){let s=/^\/metadata\/([^/]*)$/u.exec(o.path)?.[1],c=s!==void 0&&!Object.hasOwn(r.metadata,s.replaceAll("~1","/").replaceAll("~0","~"));if(c&&o.op==="remove")continue;let d=c&&o.op==="replace"?{...o,op:"add"}:o,l=qn(r,[d]);if(!l.ok)throw new g(`History union cannot rebase a scalar patch at ${n.branch} line ${n.line} (${n.op}), operation ${a+1} ${o.op} ${o.path}; preserve the source histories for manual recovery.`,y.CONFLICT,{code:"history_union_rebase_conflict",field:o.path,history_merge:{...n,patch_index:a,patch_path:o.path},nextSteps:["Preserve all three history inputs and both item snapshots. Review the named branch event against the merged replay state; do not drop the event or concatenate unchecked patches. After resolving the history and item deliberately, run pm history <id> --verify and pm merge reconcile --dry-run before committing."]});r=l.document}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]="425ef2aa-56fa-5d06-b8d0-316373ad2433")}catch{}})();var sS=Object.freeze({pm_item_scalar_missing:!0});function Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function V(e){return e===void 0?sS:e}function At(e){return xe(A(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function ms(e,t){let n=$e(e);if(n)throw new g(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let i=[];for(let[r,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(o)try{let s=JSON.parse(o);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");i.push(s)}catch{throw new g(`History merge input (${t}) contains invalid JSON at line ${r+1}.`,y.GENERIC_FAILURE)}}return i}function ze(e){return A({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function cS(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&ze(e[i])===ze(t[i]);)i+=1;return i}function dS(e,t,n,i){let r=[...e,...n],a=new Map(r.map((u,m)=>[u,m])),o=new Map(r.map((u,m)=>[ze(u),m])),s=r.map(()=>new Set);for(let u of[e,t]){let m=u.map(f=>a.get(f)??o.get(ze(f)));for(let f=1;f<m.length;f+=1)m[f-1]!==m[f]&&s[m[f-1]].add(m[f])}let c=r.map(()=>0);for(let u of s)for(let m of u)c[m]+=1;let d=r.map((u,m)=>m).filter(u=>c[u]===0),l=[];for(;d.length>0;){d.sort((m,f)=>{let p=r[m],h=r[f],_=Lt(p.ts,h.ts),w=ze(p),v=ze(h);return _||Number(i.has(v))-Number(i.has(w))});let u=d.shift();l.push(r[u]);for(let m of s[u])c[m]-=1,c[m]===0&&d.push(m)}if(l.length!==r.length)throw new g("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",y.GENERIC_FAILURE);return l}function Sf(e){return{entries:e,positions:new Map(e.map((t,n)=>[ze(t),n])),index:-1,document:ar()}}function ys(e,t){let n=t??e.index;for(;e.index<n;){let i=qn(e.document,e.entries[e.index+1].patch);if(!i.ok)throw new g("History union cannot preserve a patch that does not apply in its original branch.",y.GENERIC_FAILURE);e.document=i.document,e.index+=1}return e.document}function xf(e,t){if(t!==void 0&&t>e.index+1)throw new g("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",y.GENERIC_FAILURE);return ys(e,t)}function lS(e,t,n){if(n===0)return;let i=Sf(e),r=Sf(t),a=ys(i,n-1);ys(r,n-1);let o=0,s=new Set([...Rf,...Af]);return(c,d)=>{if(o++<n)return c.patch;let l=ze(c),u=xf(i,i.positions.get(l)),m=xf(r,r.positions.get(l)),f=sr(c.patch).filter(v=>{let[E,k]=v.path.slice(1).split("/");return E!=="metadata"||!s.has(k)}),p=i.positions.get(l),h=Ef(d,f,{branch:p===void 0?"theirs":"ours",line:(p??r.positions.get(l))+1,op:c.op}),_=$f(a.metadata,u.metadata,m.metadata,"ours","latest_document_update",String(u.metadata.updated_at),String(m.metadata.updated_at));for(let v of s)Object.hasOwn(_.merged,v)?h.metadata[v]=_.merged[v]:delete h.metadata[v];let w=or({metadata:h.metadata,body:h.body});return oS.compare(d,w)}}function rM(e,t,n){let i=ms(e,"base"),r=ms(t,"ours"),a=ms(n,"theirs"),o=[i,r,a].map(f=>f.filter(p=>p.op==="create"));if(o[0].length===0&&o.slice(1).every(f=>f.length>0)||o.some(f=>f.length>1)||new Set(o.flat().map(ze)).size>1)throw new g("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",y.CONFLICT,{code:"item_identity_conflict"});let s=cS(r,a);if(s===r.length&&s===a.length)return{merged:Nt(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===a.length)return{merged:Nt(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:Nt(a),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:a.length-s,entries_total:a.length,reanchored:!1};let c=r.slice(s),d=new Set(c.map(ze)),l=a.slice(s).filter(f=>!d.has(ze(f))),u=dS(c,a.slice(s),l,d),m=cr([...r.slice(0,s),...u],void 0,{continuousHashSurface:!0,projectPatch:lS(r,a,s)});if(m.skippedOps>0)throw new g(`History union cannot preserve ${m.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,y.GENERIC_FAILURE);return{merged:Nt(m.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:c.length,entries_from_theirs:l.length,entries_total:m.entries.length,reanchored:!0}}function ps(e,t){let n=$e(e);if(n)throw new g(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let i=[];for(let[r,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch{throw new g(`Relationship merge input (${t}) contains invalid JSON at line ${r+1}.`,y.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new g(`Relationship merge input (${t}) line ${r+1} is not a relationship event (eventId + sequence required).`,y.GENERIC_FAILURE);i.push(s)}return i}function Zr(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
47
47
|
`)}
|
|
48
|
-
`}function
|
|
49
|
-
`,conflict_paths:c,paths_from_theirs:d,preferred:r}}import Zr from"node:path";import{execFile as hS}from"node:child_process";import{createHash as Sf}from"node:crypto";import{readdir as _S}from"node:fs/promises";import gS from"node:path";import{promisify as yS}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]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var ut=yS(hS),Xr=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function rM(e,t,n){let i=t.trim(),r=/^(['"])(.*)\1$/su.exec(i)?.[2]??i;for(let a of["rebase-merge","rebase-apply"])try{let{stdout:o}=await ut("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Bn(o.trim(),128))?.trim();if(s===void 0||!Xr.test(s))continue;let{stdout:c}=await ut("git",["rev-parse","--verify",`${s}:${r}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:s,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(a=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(a)))try{let{stdout:a}=await ut("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!Xr.test(o))return;let{stdout:c}=await ut("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Sf(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:o,original_blob:d}}catch{}}function xf(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&Xr.test(t.original_head)&&typeof t.original_blob=="string"&&Xr.test(t.original_blob)}async function If(e,t,n,i){if(i!==void 0&&Sf(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(i)}\0`).update(i).digest("hex")!==n.original_blob)return!1;try{let{stdout:r}=await ut("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),a=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await _S(r.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await ut("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await ut("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await ut("git",["hash-object","--",gS.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await ut("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!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]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var wS=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,vS=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,ea=2048,bS=64,kS=1e5,ES=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function mt(e){return wS.test(e)}var SS=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ta="bounded_non_sensitive_scalars_v1",xS=new Set(["open","in_progress","blocked","closed","canceled"]),IS=new Set(["risk","confidence","severity"]),RS=new Set(["low","medium","high","critical"]),Af=new Map([["priority",new Set([0,1,2,3,4].map(A))],["status",new Set([...xS].map(A))],...[...IS].map(e=>[e,new Set([...RS].map(A))])]);function Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cf(e,t){return Object.keys(e).every(n=>t.has(n))}function Qr(e){return Array.isArray(e)&&e.length<=ea&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function vi(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let i=t.pop();if(n+=1,n>kS||i.depth>bS)return!1;if(Array.isArray(i.value))for(let r of i.value)t.push({value:r,depth:i.depth+1});else if(Qe(i.value))for(let r of Object.values(i.value))t.push({value:r,depth:i.depth+1})}return!0}function Tf(e){if(!Qe(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[Cf(e,SS),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),vi(e.base),vi(e.ours),vi(e.theirs),vi(e.retained),vi(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function AS(e){if(!Qe(e))return!1;let t=Object.entries(e);return t.length<=ea&&t.every(([n,i])=>n.length>0&&n.length<=256&&typeof i=="string"&&/^[a-f0-9]{64}$/u.test(i))}function CS(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||Zr.posix.isAbsolute(e))return!1;let n=Zr.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&Zr.posix.basename(n,Zr.posix.extname(n))===t}function TS(e){return!Qr(e.fields_from_theirs)||!Qr(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>ea||!e.decisions.every(Tf)?!1:e.merged_field_hashes===void 0||AS(e.merged_field_hashes)}function $S(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],i=[void 0,"clone_local","hash_only","bounded_inline","mixed"],r=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&i.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ta)&&r.includes(e.evidence_source)}function DS(e){return typeof e.created_at=="string"&&Qt(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Qt(e.reconciled_at))}function Rf(e,t){if(!Qe(t)||ra(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(r=>r==="pm_value_hash"||r==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let i=t.pm_value;return(i===null||Af.get(e)?.has(A(i))===!0)&&At(i)===t.pm_value_hash}function OS(e){if(!e.decisions.every(i=>i.base===null&&i.ours===null&&i.theirs===null&&Rf(i.field,i.retained)&&Rf(i.field,i.discarded)))return!1;let t=e.decisions.reduce((i,r)=>i+(Qe(r.retained)&&Object.hasOwn(r.retained,"pm_value")?1:0)+(Qe(r.discarded)&&Object.hasOwn(r.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===ta)}function PS(e){return e.operation!==void 0&&!xf(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function LS(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!Cf(e,ES)?"required_fields":typeof e.id!="string"||!mt(e.id)?"receipt_id":typeof e.item_id!="string"||!vS.test(e.item_id)?"item_id":CS(e.item_path,e.item_id)?null:"item_path"}function na(e,t){if(!Qe(e))return"required_fields";let n=LS(e);return n!==null?n:PS(e)?TS(e)?$S(e)?DS(e)?t==="durable"&&!OS(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function ia(e){if(!Qe(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(i=>!Qe(i)||!Object.hasOwn(i,"retained")||!Object.hasOwn(i,"discarded")?i:{base:V(void 0),ours:V(void 0),theirs:V(void 0),...i})}}function $f(e){if(!Qe(e))return;if(!Qr(e.fields_from_theirs))return"fields_from_theirs";if(!Qr(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>ea)return"decisions";let t=e.decisions.findIndex(n=>!Tf(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function ps(e,t){return na(e,t)===null}function ra(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function fs(e,t){let n=xn(t),i=At(n?void 0:t);return!n&&(t===null||Af.get(e)?.has(A(t))===!0)?{pm_value_hash:i,pm_value:t}:{pm_value_hash: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]="7bab0a8e-842c-5588-a0b2-22ef261ddb06")}catch{}})();var HS=US(NS),aa=100;async function hs(e){try{let{stdout:t}=await HS("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Pf(e,t){let n=ie.dirname(ie.resolve(e,t));for(let i=0;i<12;i+=1){if(await D(ie.join(n,"settings.json")))return n;let r=ie.dirname(n);if(r===n)break;n=r}return null}function In(e){return ie.join(e,"merge-receipts")}function Tt(e){return`${e}.json`}async function Df(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Bn(e.receiptPath,_r)}catch(a){if(gt(a))return null;throw a}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=ia(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!ps(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ie.basename(e.receiptPath)!==Tt(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:i,...r}=n;return{path:e.receiptPath,fingerprints:ki(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...r,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
50
|
-
`}}function
|
|
51
|
-
`);let o=await
|
|
52
|
-
`)}return a}async function Of(e,t){let n;try{n=await jS(e)}catch(s){let c=await qS(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let i=[],r=0,a=[],o=(s,c)=>{if(r+=1,a.length>=aa)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...mt(d)?{receipt_id:d}:{candidate_name_hash:xe(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await GS(e,s,t);c.receipt!==void 0?i.push(c.receipt):o(s,c)}return{receipts:i,invalid_evidence_count:r,invalid_evidence:a,invalid_evidence_truncated:r>a.length}}async function qS(e,t,n=FS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ie.dirname(i);if(a===i)return!0;i=a}}async function GS(e,t,n){let i;try{i=await Bn(ie.join(e,t),_r)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=ia(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=na(r,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:$f(r)}:{}};let o=r;if(t!==Tt(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function BS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-5H6RMRTK.js"),r=await JS(t),a=await i(r?.workspace??e,In(t),n.map(o=>Tt(o.id)),_r,r?.directory);return n.flatMap(o=>{try{let s=ia(JSON.parse(a.get(Tt(o.id))??""));if(na(s,"durable")!==null)return[];let c=s,d=ki(o);return c.id===o.id&&ki(c).some(l=>d.includes(l))?[o.id]:[]}catch{return[]}})}async function JS(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,i=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!i))try{if(await Ct(e)!==await Ct(i))return;let r=ie.relative(await Ct(t),await Ct(n)),a=r===".."||r.startsWith(`..${ie.sep}`)||ie.isAbsolute(r),o=In(a?ie.join(await Ct(t),".agents","pm"):await Ct(n)),[s,c]=await Promise.all([Ct(o),Ct(In(n))]);return s!==c?void 0:{workspace:t,directory:o}}catch{return}}async function pt(e,t={}){let n=await hs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Of(n,"clone_local"),r=t.pmRoot??ie.join(e,".agents","pm"),a=await Of(In(r),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of i.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?ki(u):[bi(u)]).includes(bi(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<aa&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}o.set(u.id,m===void 0?u:zS(u,m))}await WS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await BS(e,r,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...o.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:i.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...i.invalid_evidence,...a.invalid_evidence,...c].slice(0,aa),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>aa,clone_local_evidence_resolved:n!==null}}function Lf(e,t,n){let i=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),r=[...e].filter(a=>!i.has(a));if(r.length!==0)throw new g(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,y.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Rn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function CM(e,t,n={}){let i=await hs(e);if(i===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let r=t.evidence_source??"clone_local";if(!ps(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=ie.join(i,Tt(t.id)),s=await Pf(e,t.item_path),c=s===null?null:ie.join(In(s),Tt(t.id)),d=(await Promise.all([Df({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Df({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[bi(t)]:ki(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function TM(e){let t=await pt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as VS}from"node:crypto";import sa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var KS="2026-08-09T16:15:18.000Z",Mf=Symbol("pre-durable-disposition-eligible");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _s(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let i=e[n];if(!(n in e)||typeof i!="string"||i.length===0||i.length>256||i.includes("\0")||t.has(i))return!1;t.add(i)}return!0}function Nf(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 jf(e,t){if(typeof e!="string")return!1;let n=sa.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!sa.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(sa.posix.basename(n)===`${t}.toon`||sa.posix.basename(n)===`${t}.md`)}function YS(e,t){return typeof e.receipt_id=="string"&&mt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&jf(e.item_path,t)}function Ff(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,a=Array.isArray(r)?new Set(r.flatMap(o=>Nf(o)?[o.field]:[])):new Set;return _s(t)&&_s(n)&&_s(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Nf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function XS(e,t){return YS(e,t)&&Ff(e)}function ZS(e,t){return typeof e.receipt_id=="string"&&mt(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&&jf(e.item_path,t)&&Ff(e)}function QS(e){return e[Mf]===!0}function Uf(e,t){if(!ft(e)||!ft(e.context))return[];let n=e.context.merge;return!ft(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!ft(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:XS(i,t),[Mf]:ZS(i,t),...typeof e.ts=="string"&&Qt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Hf(e,t,n){if(!ft(e)||e.op!=="merge_reconcile")return[];if(!ft(e.context)||!ft(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!ft(r)||typeof r.receipt_id!="string"||!mt(r.receipt_id)||typeof r.original_history_line!="number"||!Number.isSafeInteger(r.original_history_line)||r.original_history_line<1||typeof r.original_event_ts!="string"||!Qt(r.original_event_ts)||r.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:r.receipt_id,originalHistoryLine:r.original_history_line,originalEventTimestamp:r.original_event_ts,auditHistoryLine:n,reason:r.reason}])}function zf(e,t,n=[]){let i=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;i.set(o,Math.max(i.get(o)??0,a.auditHistoryLine))}let r=a=>QS(a)&&a.eventTimestamp!==void 0&&Lt(a.eventTimestamp,KS)<0&&(i.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!r(a)).map(a=>({item_id:a.itemId,history_line:a.line,...mt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:VS("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as e0}from"node:buffer";import{readFile as t0}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]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function n0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new g("History salvage cannot discard a potentially complete record with trailing corruption.",y.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("History salvage would conceal interior corruption or a malformed record.",y.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new g("History salvage requires complete history records before the invalid tail.",y.CONFLICT,{code:"history_salvage_refused"});return n}function i0(e){if($e(e))throw new g("Resolve history merge conflicts before salvage.",y.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,i,r=0;for(let[o,s]of e.split(`
|
|
53
|
-
`).entries()){if(!s.trim()){n+=s.length+1;continue}let c=
|
|
54
|
-
`}),l.push(...await K({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:$()}}import{realpath as Kf}from"node:fs/promises";import gs from"node:path";import Yf from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6d2870f-ebba-580a-85e9-3eb44e533d08")}catch{}})();function Gf(e,t){return t==="body"?e.body:e.metadata[t]}function a0(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function o0(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function Bf(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(i=>a0(e,i)))return t;let n=t.map(i=>e==="comments"?i:o0(i));return[...new Map(n.map(i=>[A(i),i])).values()]}function ys(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let i=new Set;return e.every(r=>{let a=t.findIndex((o,s)=>!i.has(s)&&ys(r,o));return a<0?!1:(i.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([i,r])=>Object.hasOwn(n,i)&&ys(r,n[i]))}function Jf(e,t){let n=new Set(t),i=[];for(let r=e.length-1;r>=0&&n.size>0;r-=1){let a=e[r],o=new Set;for(let c of ar(a.patch))o.add(sr(c.path)),c.from&&o.add(sr(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);i.push({index:r+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return i.reverse()}function s0(e,t,n){let i=Yf.compare(t,n);if(i.length===0)return;let r=new Set;for(let p of i)r.add(sr(p.path));let a=new Set([...r].filter(p=>ys(Bf(p,Gf(t,p)),Bf(p,Gf(n,p))))),o=new Set([...r].filter(p=>!a.has(p))),s=Jf(e,o),c=Jf(e,a),d=[...r].sort((p,h)=>p.localeCompare(h)),l=[...o].sort((p,h)=>p.localeCompare(h)),u=[...a].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:r.size,reconciled_fields:d,reverted_field_count:o.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function c0(e){try{return await Kf(e)}catch{return null}}async function d0(e){if(await c0(gs.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let i=Object.keys(n).sort();if(t.length!==i.length||t.some((a,o)=>a!==i[o]))return null;let r=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:r[a];return[At(o),xe(A(V(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function l0(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Kf(e.itemPath),i=[];for(let o of t){let s=await d0({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&i.push(s)}let r=new Set(i.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return i.length>0&&(a===void 0||a.length>0&&a.every(o=>r.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:i.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Vf(e,t,n,i){if(e===void 0)return;let{receipt:r,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:gs.relative(a,t.currentItemPath).split(gs.sep).join("/");if(!n||i.entriesRehashed!==0||i.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==r.item_path||r.operation===void 0||!await If(a,r.item_path,r.operation,t.currentItemRawBeforeLock))throw new g("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function u0(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),n=e.options.mergeReceiptProof?await pt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,i=n?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[];Lf(t,n,e.options.dryRun===!0);let r=e.options.mergeReceiptProof?await l0({proof:{...e.options.mergeReceiptProof,receipts:i},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new g(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let a=r?.trusted?i.filter(o=>r.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:a.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:a.map(oa)}}:e.options.auditContext}}function m0(e,t,n){let i=e.located?.itemPath??null,r=t.loadedItem,a=t.entries;if(!r)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=rr(r.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:tn(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:r.raw,loadedItem:r}}function p0(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function f0(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,i=Re(e.reanchorEntries.at(-1)?.hash_algorithm),r=tn(e.finalReplay,e.itemHashVersion,i),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(a),s=tn(n,e.itemHashVersion,i),c={hash_algorithm:i,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Yf.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(nr({...c,event_class:Nd(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function h0(e,t,n){let i=[];return e||i.push("history_repair_no_changes"),t>0&&i.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&i.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),i}async function ws(e,t,n){let{pmRoot:i,settings:r,typeRegistry:a}=await Xa(n.path),o=await Rl(i,e,r,a.type_to_folder);return t.salvageTail===!0?qf({pmRoot:i,subject:o,settings:r,typeRegistry:a,options:t,author:z(t.author,r.author_default)}):Au({pmRoot:i,subject:o,settings:r,typeRegistry:a,operation:"history-repair",options:t,transform:s=>g0({pmRoot:i,subject:o,options:t},s)})}function _0(e,t,n){let i=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(r=>r.record_hash_version!==void 0&&r.op==="merge_reconcile"&&A(r.context)===A(n));return e.forceAuditEntry===!0&&!i}async function g0(e,t){let{pmRoot:n,subject:i,options:r}=e,a=t.entries,o=t.verification,s=bt(a),c=r.normalizeProvenance?ku(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=Wd(c.entries),l=new Set(c.entries.map(P=>P.item_hash_version).filter(P=>P!==void 0)),u=or(c.entries,d),m=m0(i,t,d);await Vf(r.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=tn(f,d),h=!1;if(m.currentItemReplay!==null){let P=tn(m.currentItemReplay,d);h=!p.some((x,q)=>x===P[q])}let _=h&&m.currentItemReplay?s0(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await u0({options:r,pmRoot:n,subjectId:i.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,_0(r,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,I=!!r.dryRun,C=p0({message:r.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=f0({reanchorEntries:u.entries,changed:E,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:C,auditOperation:r.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),O=h0(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>Vf(r.mergeAbandonmentProof,m,o.ok,u),report:({verification:P,warnings:x})=>({id:i.id,dry_run:I,changed:E,history:{path:i.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:P.ok,verify_errors:P.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:r.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...O,...x])].sort((q,Se)=>q.localeCompare(Se)),generated_at:$()})}}function Ej(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function Sj(e,t){if(e.salvageTail===!0)throw new g("Tail salvage requires one explicit item ID; --all is not supported.",y.USAGE);let{pmRoot:n,settings:i,typeRegistry:r}=await Xa(t.path),a=[],o=await rt(n,i.item_format,r.type_to_folder,a,i.schema,{forceSourceScan:!0}),s=await Ut(n,o),c=e.normalizeProvenance?await Eu(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await ws(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(_=>`${f}:${_}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await Md(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_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]="11486e17-e6da-5770-8621-f59a17bb4922")}catch{}})();var y0=new Set(yl),Xf=25,w0=be.join("runtime","telemetry","events.jsonl"),v0=be.join("runtime","telemetry","state.json"),b0=2500,k0=500,Zf=kl-3,E0=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function xs(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 Is(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function An(e){return e.trim().toLowerCase()}function ks(e,t){let n=An(e),i=An(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Rs(e){try{return(await ht.stat(e)).isDirectory()}catch{return!1}}async function S0(e){let t=(await ht.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>ht.readdir(be.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>jn.some(a=>r.name.endsWith(a))).map(r=>be.parse(r.name).name)))}async function x0(e,t,n,i){let r=await Ne({path:e,scope:"project"}),a=t!=="_workspace"&&!i.has(t);if(!n.enabled&&!a)return{warnings:r,overThreshold:!1,classification:"live"};let o;try{o=await ht.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function I0(e,t,n){let i=be.join(e,"history");if(!await Rs(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ht.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),a=t.enabled?t.max_entries:null,o=[],s=[],c=[],d=[];for(let l of r){let u=be.join(i,l),m=l.slice(0,-6),f=await x0(u,m,t,n);o.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&d.push(m),f.overThreshold&&s.push(m)}return{count:r.length,warnings:[...o,...s.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:s,max_entries:a,tombstones:c,orphaned:d}}function Es(e,t){return be.relative(e,t).replaceAll("\\","/")}async function Qf(e,t){let n=[...new Set(Object.values(t))].sort((r,a)=>r.localeCompare(a)),i=[];for(let r of n){let a=be.join(e,r),o=[];try{o=await ht.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&j(s))continue;continue}for(let s of o)jn.some(c=>s.toLowerCase().endsWith(c))&&i.push(be.join(a,s))}return i.sort((r,a)=>Es(e,r).localeCompare(Es(e,a))),i}function R0(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function A0(e,t,n){let i=await Qf(e,t),r=[],a=[],o=[],s=[],c=Gt(F());for(let d of i){let l=Es(e,d),u;try{u=await ht.readFile(d,"utf8")}catch{r.push(l);continue}let m=$e(u);if(m){a.push({path:l,...m});continue}try{let f=vt(u,{format:$c(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:Zi(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function C0(e){let t=be.join(e,"history"),n=[],i=[],r=[],a=[],o=[],s=[];try{s=(await ht.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){R0(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await ht.readFile(be.join(t,c),"utf8")}catch{n.push(d);continue}let u=$e(l);if(u){i.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...Uf(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Hf(p,d,f+1))}catch{r.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:i,invalidJson:r,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function eh(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 T0(e,t,n,i,r,a){let o=await A0(e,t,n),s=await C0(e),c=Qi(o.formatVersions,Hn,Xi),d=fe(n),l=hr(a,x=>Dd(x,d),Gn()),u=await Kr(e),m=await Et(e),f=await uf(e,m),p=await mf(e,m,i,r),h=m===null?null:await dn(m),_=await pt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(_.durable_receipt_ids),v=zf(s.mergeReceiptReferences,w,s.mergeReceiptDispositions),E=v.missing,k=_.receipts.filter(x=>x.state==="pending"),{pendingDecisions:I,lossless:C}=Rn(k),S=h?.status==="missing"&&h.missing_keys.length===5&&h.drifted_keys.length===0,b=[...o.unreadable.map(x=>`integrity_item_unreadable:${x}`),...o.conflictMarkers.map(x=>`integrity_item_conflict_marker:${x.path}:L${x.line}`),...o.parseFailures.map(x=>`integrity_item_parse_failed:${x}`),...s.unreadable.map(x=>`integrity_history_unreadable:${x}`),...s.conflictMarkers.map(x=>`integrity_history_conflict_marker:${x.id}:L${x.line}`),...s.invalidJson.map(x=>`integrity_history_invalid_json:${x.id}:L${x.line}`),...c.outdated.map(x=>`integrity_item_outdated_format_version:${x}`),...c.ahead.map(x=>`integrity_item_ahead_format_version:${x}`),...eh(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...h!==null&&h.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${h.missing_keys.length+h.drifted_keys.length}`]:[],...p.warnings,...f.warnings,...I.length>0?[`merge_decisions_unreviewed:${I.length}`]:[],...C.length>0?[`merge_receipts_pending:${C.length}`]:[],...pf({invalidEvidenceCount:_.invalid_evidence_count,missingHistoryReferenceCount:E.length})],O=[...new Set(b)].sort((x,q)=>x.localeCompare(q)),P=O.filter(x=>!x.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:P.length===0?"ok":"warn",ok:P.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.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:h===null||h.status==="ok"?0:h.missing_keys.length+h.drifted_keys.length,merge_fence:p.count,ignored_merge_artifacts:f.rules.length,pending_merge_decisions:I.length,lossless_merge_receipts:C.length,invalid_merge_receipt_evidence:_.invalid_evidence_count,missing_merge_receipt_history_references:E.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.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:je(l.relations,Tu)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.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:h===null?null:{...h,required:r},merge_fence:p.audit,ignored_merge_artifacts:f.rules,pending_merge_decision_items:[...new Set(I.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),lossless_merge_receipt_items:[...new Set(C.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),invalid_merge_receipt_evidence_details:_.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:_.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:E.slice(0,fo),missing_merge_receipt_history_reference_details_truncated:E.length>fo}},warnings:O,gitWorkspaceRoot:m,pendingMergeReceipts:k}}function $0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function D0(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:$0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function O0(e,t){return Y(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function P0(e){let t=Y(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function L0(e){return Y(e.reason)??Y(e.error)??Y(e.message)}function vs(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let i=(e.name??"").localeCompare(t.name??"");return i!==0?i:(e.id??"").localeCompare(t.id??"")}function N0(e){let t=[],n=[],i=[];e.forEach((a,o)=>{let s=O0(a.definition,o),c=P0(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){i.push({layer:a.layer,name:a.name,id:s,status:c,reason:L0(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(vs),n.sort(vs),i.sort(vs);let r=[...i.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:i,applied_count:t.length,pending_count:n.length,failed_count:i.length},warnings:r}}function th(e,t,n,i,r,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>Is(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=d.map(ri).filter(_=>_!==void 0),h=Jo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(i.failed_count>0||i.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Li.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.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&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.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:i.failed_count,migration_pending_count:i.pending_count,managed_state_warning_count:r,managed_extension_entries_count:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function M0(e,t,n){let i=await es(Ge(e)),r=await Be({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(S=>D0(S)),o=await vu(r.loaded,Ge(e)),s=await Je({...r,loaded:r.loaded}),[c,d]=await Promise.all([he(r.roots.project),he(r.roots.global)]);await Qo(e,s.registrations.migrations);let l=N0(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.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}}},m=new Set(c.state.entries.map(S=>An(S.name))),f=new Set(d.state.entries.map(S=>An(S.name))),p=[...new Map(r.loaded.filter(S=>!(S.layer==="project"?m:f).has(An(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let O=`${S.layer}:${S.name}`,P=`${b.layer}:${b.name}`;return O.localeCompare(P)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),_=p.filter(S=>ks(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!ks(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],E=[...i.warnings,...r.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=hi(E),I=_i(),C=th(E,r.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,_,w);return{check:{name:"extensions",status:E.length===0?"ok":"warn",ok:E.length===0,details:{...r,loaded:a,warnings:E,activation:u,author_manifest:i,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:I,capability_guidance:k,host_version_census:o}},warnings:E}}function Ss(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=$u(e,Xf);return{values:n.values,truncated:n.truncated,total:e.length}}function ca(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function j0(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return y0.has(e)?e:null}function da(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 nh(e){let t=0,n=0,i=0,r=0,a=0;for(let o of e.split(`
|
|
55
|
-
`)){let s=o.trim();if(s.length!==0){i+=1;try{let c=JSON.parse(s);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,a=Math.max(a,d),d>=Zf&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:a}}function F0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function U0(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 H0(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Ka().telemetry_disabled?void 0:{attempted:!0,...await ih(n)}}function z0(e,t,n){let i=[];if(t.invalidRows>0&&i.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return i;let r=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!r||a>r),s=!r,c=t.validEntries>=k0;return(o||s||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function W0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function q0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>bl?[`telemetry_schema_version_behind:${t}`]:[]}function G0(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,i=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&r&&(!i||r>=i)?[`telemetry_otel_export_failing:${n}`]:[]}function B0(){return{...Ka(),pm_no_telemetry:ca("PM_NO_TELEMETRY"),telemetry_otel_disabled:ca("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ca("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:j0()}}function J0(e,t){return e.telemetry.enabled&&t.validEntries>0}function V0(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function ih(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(b0)});return{probe_url:da(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of E0){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:da(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function K0(e,t){let n=ji(process.cwd()),i=be.join(n,w0),r=be.join(n,v0),a=await B(i),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?nh(a):F0(),d=await B(r),{runtimeState:l,stateParseFailed:u}=U0(d),m=e.telemetry.endpoint.trim(),f=da(m),p=await H0(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...z0(e,c,l),...W0(p),...q0(p),...G0(e,l));let _=J0(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:i,queue_exists:o,queue_entries:c.validEntries,queue_draining:V0(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Zf,queue_max_attempts:c.maxAttempts,runtime_state_path:r,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:p??{attempted:!1},env_overrides:B0()}},warnings:h}}async function Y0(e){let t;try{t=await Qu(e)}catch(i){let r=i instanceof Error?i.message:String(i);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:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}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 X0(e){let t="metadata",n=e.items,i=await Ut(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(r.length>0){n=await rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Ut(e.pmRoot,n),a=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,E)=>v.localeCompare(E));let w=new Set(a);o=r.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=i,_=[...s.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}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:r.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function Z0(e,t){let n=ur(e),i=qn(n.settings),r=fr(n.settings,t),a=i.active?Mt(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(i.active&&r.active)}}function Q0(){return{refreshed:[],skipped:[],warnings:[]}}async function ex(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Q0():gl(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function tx(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&an(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function nx(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,i)=>n.localeCompare(i))}function ix(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function rh(e,t){let n=t.providerResolution.active?.name??null,i=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Ba(n,e.search?.provider??null),vector_store_active:i,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Ba(i,e.vector_store?.adapter??null)}}function rx(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function ax(e,t,n){return e.enabled&&n.length>0&&t}async function ox(e,t,n,i,r){let a=Z0(t,e),o=await on(e),s=a.semanticRuntimeAvailable?Za(n,o.entries):[],c=await ex({pmRoot:e,snapshot:a,refreshPolicy:i,staleBefore:s}),d=await on(e),l=a.semanticRuntimeAvailable?Za(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=tx({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=nx({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Ss(s,r),h=Ss(l,r),_=ax(i,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:rx(i),...rh(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:Xf,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:ix(i,a.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function sx(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 ah(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new g("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new g("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var cx=new Set(["extensions","locks","search"]);function dx(e){let t=new Set(bc.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(kc));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of cx)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,a)=>r.localeCompare(a)),optionalDirs:[...n].sort((r,a)=>r.localeCompare(a)),optionalDirSet:n}}async function lx(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:a}=dx(t),o=[],s=[],c=[];for(let d of[...i,...r]){let l=be.join(e,d);c.push(...await Ne({path:l,scope:"project"})),!await Rs(l)&&(a.has(d)?s.push(d):o.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function oh(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,i=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||i)&&e.full!==!0,skipDrift:(e.skipDrift===!0||i)&&e.full!==!0,skipVectors:(e.skipVectors===!0||i)&&e.full!==!0}}async function ux(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?it(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function bs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function mx(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 px(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 fx(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 As=e=>e.unknown_event_count??0,Cs=e=>e.actionable_unknown_event_count??As(e);function hx(e,t,n,i,r,a){let o=As(i),s=Cs(i),c=o>0,d=s>0,l=r.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:i}:{},...l?{stale_in_progress:r}:{},...a.outcomes.length>0?{provenance_resolver_outcomes:a.outcomes}:{},...a.invalid_values.length>0?{provenance_invalid_values:a.invalid_values}:{},provenance_sample:a.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 sh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function _x(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 gx(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function yx(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 ch(e){let t=new Map;for(let[i,r]of Object.entries(e.remediationSources))for(let a of r)t.has(a)||t.set(a,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let r=t.get(i)??"integrity",a=ko(i)?.code??Is(i),o=n.get(r)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=ri(i)??(a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a]),d=xs(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:a,check:r,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function wx(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 vx(e){for(let t of e.checks){let n=Eo(e.remediationSources[t.name]);wx({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function bx(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"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),r=new Map;for(let o of e.pendingMergeReceipts){let s=r.get(o.item_id)??[];s.push(o),r.set(o.item_id,s)}let a=[];for(let o of n){if(i.has(o))continue;let s=r.get(o);if(!(!s||s.length===0))try{await ws(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),a.push(o)}catch{}}return[...new Set(a)].sort((o,s)=>o.localeCompare(s))}function kx(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(i=>i.startsWith("history_drift_hash_mismatch:")?!n.has(i.slice(i.indexOf(":")+1)):!0),...t.map(i=>`history_drift_merge_receipt:${i}`)].sort((i,r)=>i.localeCompare(r)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function dh(e,t={}){let n=M(process.cwd(),e.path);await te(n);let i=Bt(n),{settings:r,warnings:a}=await Vd(n),o=[...new Set(a)],s=H(r,F()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=ah(t),m=await lx(n,s,c),f=sx(r),p=await K0(r,{checkTelemetry:t.checkTelemetry===!0}),h=await M0(n,r,!!e.noExtensions),_=oh(t),w=[],v=await ux({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Rr(fe(r.schema),v),I=[...(await Hu({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ue=>ue.startsWith("agent_guidance_")),...f,...Ar(k)],C=_.skipDrift?{warnings:[]}:await qd({pmRoot:n,settings:r,itemIds:v.map(ue=>ue.id),commandLabel:"health"}),S=await I0(n,r.history.compact_policy,await S0(n)),b=await Qn(n,20,t.verboseAuthorEvents===!0),O=Cs(b),P=O>0?[`history_unknown_author_events:${O}`]:[],x=sh(await wl(n,v,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),q=await Iu(n),Se=q.warnings,_e=await Y0(n),pe=_.skipIntegrity&&!l?{...bs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await T0(n,s.type_to_folder,r.schema,r,l,v),Le=_.skipDrift?bs("history_drift"):await X0({pmRoot:n,items:E,settings:r,typeRegistry:s,itemReadWarnings:w}),Di=[...new Set(w)],Nn=await bx({gitWorkspaceRoot:pe.gitWorkspaceRoot,pendingMergeReceipts:pe.pendingMergeReceipts,historyDriftCheck:Le,global:e});kx(Le,Nn);let U=_.skipVectors?bs("vectorization"):await ox(n,r,E,u,t.verboseStaleItems===!0),G=[mx(i,r,o),px(m,c),fx(I,k),p.check,h.check,hx(v,r,S,b,x.scan,q),_e.check,pe.check,Le.check,U.check],Oi=_x({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Di,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U}),Pi=yx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Di,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U});vx({checks:G,remediationSources:Pi,historyDriftedCount:gx(Le),overThresholdCount:S.over_threshold.length});let Aa=Oi.filter(ue=>!xs(ue,l)),Ca=ch({warnings:Oi,checks:G,remediationSources:Pi,requireMergeDrivers:l}),ag=new Set(Ca.filter(ue=>ue.severity==="gate_failing").map(ue=>ue.check)),og=new Set(Ca.map(ue=>ue.check));for(let ue of G)ue.ok=!ag.has(ue.name),og.has(ue.name)&&(ue.status="warn");let sg={ok:Aa.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Aa.length>0?y.GENERIC_FAILURE:0},checks:G,warnings:Oi,findings:Ca,failed_because:Aa,generated_at:$()};return go(sg,t,_.summaryMode)}var S1={buildHierarchyIntegrityWarnings:eh,buildExtensionHealthTriageSummary:th,buildHealthFindings:ch,buildCapabilityContractMetadata:_i,buildStaleInProgressHealthSummary:sh,buildVectorizationProviderDetails:rh,collectUnknownCapabilityGuidance:hi,isAdvisoryHealthWarning:xs,isDirectory:Rs,isExpectedUnmanagedExtension:ks,listItemDocumentPaths:Qf,normalizeEndpointForDisplay:da,normalizeExtensionNameForMatch:An,parseTelemetryQueue:nh,probeTelemetryEndpointHealth:ih,projectHealthResult:go,resolveActionableUnknownAuthorEventCount:Cs,resolveHealthSkipPolicy:oh,resolveUnknownAuthorEventCount:As,resolveVectorRefreshPolicy:ah,selectStaleItemDetail:Ss,summarizeHealthCheckDetails:ho,summarizeExtensionList:ti,summarizeRecordList:je,summarizeStringList:W,telemetryEnvFlagEnabled:ca,warningCode:Is};(function(){try{var e=typeof window<"u"?window:typeof 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 lh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Al(e,t).ok)return{reason:"unverified_history"};let i=ir(),r={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(i.metadata.status));i=Yd(i,o.patch,a+1,o.op),n.has(String(i.metadata.status))?s||(r=["create","close","cancel","update","update_audit"].includes(o.op)&&wt(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):r={reason:"no_proven_transition"}}return r}function uh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function mh(e,t,n,i,r){let a=uh(n),o=t.filter(d=>a.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of i?o:[]){let l;try{let u=await nt(Ot(e,d.id),d.id),{body:m,...f}=d;l=lh(u,{metadata:f,body:m},a)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}s.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,r).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>r,closure_history_inspected:i,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,r),closure_timestamp_residual_truncated:c.length>r,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function ph(e,t){let n=M(process.cwd(),t.path),i=await T(n),r=fe(i.schema);await at({pmRoot:n,settings:i,id:e.item_id,op:"update",author:z(t.author,i.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await nt(Ot(n,a.metadata.id),a.metadata.id),s=uh(r),c=lh(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new g("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",y.GENERIC_FAILURE);return a.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 Ex(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function fh(e){return`${e.item_id} ${e.link_kind}`}function hh(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Ex(r.classification,i.classification),r.owners.set(fh(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[fh(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.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 _h(e,t,n,i,r=40){let a=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,o=new Map(t.map(d=>[d.path,d])),s={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=hh(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=er(f.status,i)??f.status;i.terminal_statuses.has(p)?(u.push(f),p===i.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,a),items_truncated:d.items.length>a}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import Cn from"node:fs/promises";import Tn 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 Sx(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let a;try{a=await Cn.readdir(Tn.join(e,r))}catch{return}for(let o of a)for(let s of jn)if(o.toLowerCase().endsWith(s)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-s.length)});break}})),i.sort((r,a)=>r.relativePath.localeCompare(a.relativePath))}function xx(e,t){let{id:n,relativePath:i,liveItemIds:r,out:a}=e,o=$e(t);if(o){a.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=Ix(e,t);s!==null&&(s.op==="delete"&&r.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function Ix(e,t){let{id:n,relativePath:i,out:r}=e,a=null,o=!1,s=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of s){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");a=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)return r.unparseable.push({id:n,path:i,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return a}function Ts(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 Rx(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await Cn.readdir(Tn.join(e,"history"))}catch{return n}for(let r of i.sort((a,o)=>a.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await Cn.readFile(Tn.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ts("history stream",o)});continue}xx({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},a)}return n}function gh(e){let t=$e(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 Ax(e){let t=[],n=0,i=null;try{i=await B(Bt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Ts("configuration file",a)})}if(i!==null){n+=1;let a=gh(i);a!==null&&t.push({path:"settings.json",detail:a})}let r;try{r=await Cn.readdir(Tn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of r.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await Cn.readFile(Tn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Ts("configuration file",c)});continue}let s=gh(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function yh(e,t,n,i={}){let r=await Sx(e,n),a=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Tn.join(e,u.relativePath);return vt(await Cn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Rx(e,a),l=await Ax(e);return{item_files_on_disk:r.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,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 nc from"node:fs/promises";import{realpathSync as HI}from"node:fs";import{execFile as zI}from"node:child_process";import Ee from"node:path";import{promisify as WI}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 Cx=["metadata","resolution"],$s=["metadata","resolution","estimates","timestamps","lifecycle"],Tx="completed";function Ds(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function wh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function vh(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=wh(n.close_reason)??Tx;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${Ds(i)}`,gate:"resolution"})}return t}function bh(e){let t=[];for(let n of e){let i=wh(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${Ds(i)}`,gate:"metadata"})}return t}function kh(e,t){return e.map(n=>{let i=Bd(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function Eh(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 Sh(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=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 ${i} ${n.item_id} --remove ${Ds(n.path)}`})}return t}function xh(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new g(`--fix-scope values must not be empty. Supported values: ${$s.join(", ")}.`,y.USAGE);return new Set(Cx)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if($s.includes(r)){n.add(r);continue}throw new g(`Unknown --fix-scope value "${i}". Supported values: ${$s.join(", ")}.`,y.USAGE)}return n}function Ih(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function Ei(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 $x=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function Dx(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=$x.exec(n);if(!i)return null;let r=i[1],a=r.toUpperCase(),o=r.slice(0,r.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(r.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${a}`)||d.includes(`ISSUE CODE \`${a}\``)||d.includes(`\`${a}\``)||d.includes(`[${a}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(o.toUpperCase())||l?a:null}function Rh(e){return typeof e=="string"&&e.trim().length>0}function Ox(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,i=new Map;for(let o of e){let s=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(d=>d!==s&&t.has(d)));n.set(s,c);for(let d of c){let l=i.get(d)??[];l.push(s),i.set(d,l)}}let r=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<r.length;o+=1)for(let s of i.get(r[o])??[]){let c=n.get(s);c.delete(r[o]),c.size===0&&(a.add(s),r.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function Ah(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||Rh(r.duplicate_of))continue;let a=Dx(r.title,{...t,evidenceText:r.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===r.id)||o.push({id:r.id,title:r.title,parent:Rh(r.parent)?r.parent.trim():null,derivations:(r.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==r.id.toLowerCase())})}let i=[];for(let[r,a]of n){if(a.length<2)continue;let o=Ox(a);if(o.length<2)continue;let s=[...o].sort((c,d)=>c.id.localeCompare(d.id));i.push({code:r,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return i.sort((r,a)=>r.code.localeCompare(a.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 Ch(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,a)=>r.localeCompare(a))){let r=t.get(i),a={};for(let o of[...r.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=r.get(o);n[i]=a}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 Th(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function $h(e,t,n=3){let i=Number.isFinite(n)&&n>=1?Math.floor(n):3,r=new Map;for(let a of t){let o=Th(a);if(o.length===0)continue;let s=r.get(o);s?s.push(a):r.set(o,[a])}return e.map(a=>{if(a.includes(",")||a.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:a,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(r.get(Th(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Dh(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]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var Px=/^[a-z][a-z0-9+.-]+:\/\//i;function Si(e){return Px.test(e.trim())}import Lx from"node:fs/promises";import ke from"node:path";import{glob as Nx}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]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var Mx=["path","scope","note"],jx=["pattern","glob","path","scope","note"],Fx=["path"],Ux=["from","to"],Hx=new Set(["note","scope"]);function Ph(e){let t=e??"project";if(!Ta.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Ta.join(", ")} (default: project).`,y.USAGE);return t}function Os(e){if(e.startsWith("```")||e.includes(`
|
|
56
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),i=n.indexOf("=");return i>=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(r=>r>=0&&r<i))?!1:n.includes("=")||bd(e)}function zx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Wx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Os(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let a=e.slice(t+2,-1).trim();if(a.length>0&&zx(a))return{path:a,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let i=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(!(i.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(r)))return{path:r,scope:"project",note:i}}function qx(e,t){return e?e.flatMap(n=>{let i=n.trim();if(t==="doc"){let a=Wx(i);if(a!==void 0)return[a]}kd(i,"--add",`${t} path`,Os(i));let r=Os(i)?Fn(n,"--add"):{path:i};if(Un(r,"--add",Mx),!r.path)throw new g(`--add requires path=<value> or a bare ${t} path`,y.USAGE);return[{path:r.path,scope:Ph(r.scope),note:r.note?.trim()||void 0}]}):[]}function Gx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--add-glob requires a glob pattern value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=Fn(n,"--add-glob");Un(i,"--add-glob",jx);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new g("--add-glob key/value form requires pattern=<glob>",y.USAGE);return{pattern:r,scope:Ph(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Bx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--remove requires a path value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=Fn(n,"--remove"),r=Object.keys(i).filter(a=>Hx.has(a.toLowerCase()));if(r.length>0)throw new g(`--remove identifies a linked artifact by path only and does not accept ${r.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,y.USAGE);if(Un(i,"--remove",Fx),!i.path)throw new g("--remove key/value form requires path=<value>",y.USAGE);return i.path}return n}):[]}function Jx(e){return e?e.map(t=>{let n=Fn(t,"--migrate");Un(n,"--migrate",Ux);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new g("--migrate requires from=<value> and to=<value>",y.USAGE);return{from:i,to:r}}):[]}function xi(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function Vx(e,t,n=[]){if(e.length===0||t.length===0)return;let i=new Set(e.map(a=>xi(a.path,n))),r=[...new Set(t.map(a=>xi(a,n)).filter(a=>i.has(a)))].sort((a,o)=>a.localeCompare(o));if(r.length!==0)throw new g(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${r.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,y.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(ke.sep).join("/")}function Ps(e,t,n=process.cwd()){let i=e.trim();if(Si(i))return i;if(ke.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return _t(i.replaceAll("\\",ke.sep));let r=ke.relative(t,n);return r.startsWith(`..${ke.sep}`)||r===".."||ke.isAbsolute(r)?_t(ke.normalize(i)):_t(ke.relative(t,ke.resolve(n,i)))}async function Kx(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){if(ke.resolve(n,r.pattern)===ke.resolve(n))continue;let a=ke.isAbsolute(r.pattern),o=await Nx(r.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>Ps(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of s)i.push({path:c,scope:r.scope,note:r.note})}return i}function Yx(e,t,n){if(t===void 0)return e;if(!n)throw new g("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",y.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function Xx(e){return`${e.path}::${e.scope}`}function Ls(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function Ns(e){return[...new Map(e.map(t=>[Xx(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Zx(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),i=[],r=[],a=[],o=[];for(let s of n){if(Si(s)){o.push(s.trim());continue}let c=ke.isAbsolute(s)?s:ke.resolve(t,s);try{(await Lx.stat(c)).isFile()?i.push(s):a.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&>(d)){r.push(s);continue}a.push(s)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:a,remote_references:o}}function Qx(e,t,n,i){let r=0;for(let a=0;a<e.length;a+=1){let o=xi(e[a].path,i);o!==e[a].path&&(e[a]={...e[a],path:o},r+=1)}return{adds:t.map(a=>{let o=xi(a.path,i);return o!==a.path&&(r+=1),{...a,path:o}}),removes:n.map(a=>xi(a,i)),count:r}}function eI(e,t,n,i){let r=Ns(e);for(let a of t){let o=r.findIndex(s=>s.path===a.path&&s.scope===a.scope);o<0?r.push(a):a.note!==void 0&&(r[o]={...r[o],note:a.note})}if(n.length>0)for(let a=r.length-1;a>=0;a-=1)n.includes(r[a].path)&&r.splice(a,1);return i?r:Ls(r)}async function Oh(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 Zx(t,e.workspaceRoot):void 0}}async function la(e,t,n,i){let{metadataKey:r}=i,a=Ed(),o=M(process.cwd(),n.path),s=Ge(o),c=process.cwd();await te(o);let d=await T(o),l=H(d,F()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),p=await a.resolveList(t.migrate,"--migrate"),h=qx(u,i.bareNoun).map(P=>({...P,path:Ps(P.path,s,c)})),_=Gx(m),w=await Kx(_,s,c),v=Yx([...h,...w],t.note,h.length>0||_.length>0),E=Bx(f).map(P=>Ps(P,s,c)),k=Jx(p);if(Vx(v,E,k),!(v.length>0||E.length>0||k.length>0)){let P=await ge(o,e,d.id_prefix,d.item_format,l.type_to_folder);if(!P)throw new g(`Item ${e} not found`,y.NOT_FOUND);let x=(await ye(P,{schema:d.schema})).document.metadata[r]??[];return Oh({id:P.id,artifacts:x,changed:!1,options:t,workspaceRoot:s})}let I=z(t.author,d.author_default),C=await at({pmRoot:o,settings:d,id:e,op:i.op,author:I,message:t.message,force:t.force,skipNoop:!0,mutate(P){let x=P.metadata,q=x[r]??[],Se=[...q],_e=Qx(Se,v,E,k),pe=eI(Se,_e.adds,_e.removes,i.supportsAppendStable&&t.appendStable===!0);pe.length>0?x[r]=pe:delete x[r];let Le=!Oc(q,pe);return{changedFields:Le?[r]:[],warnings:Le&&_e.count>0?[`path_migrations_applied:${_e.count}`]:[]}}}),S=C.item[r]??[],b=C.warnings.find(P=>P.startsWith("path_migrations_applied:")),O=b?Number(b.slice(24)):0;return Oh({id:C.item.id,artifacts:S,changed:C.changedFields.includes(r),migrationsApplied:O,options:t,workspaceRoot:s})}function ua(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=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]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function Lh(e,t,n){let i=await la(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ua(i,"docs")}import Nh from"node:fs/promises";import Pe 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 tI=32768;function Ms(e){return _t(Pe.normalize(e))}async function ma(e){try{return await Nh.realpath(e)}catch{return Pe.resolve(e)}}function $n(e,t){let n=Pe.isAbsolute(e.path)?Pe.resolve(e.path):Pe.resolve(t,e.path);return`${Ms(n)}::${e.scope}`}function pa(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>pa(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))pa(r,t?`${t}.${i}`:i,n)}function nI(e){let t=[];return pa(e.metadata,"metadata",t),pa(e.body,"body",t),t}function iI(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 rI(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{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 r of e){let a=new Set,o=r.value.slice(0,tI);for(let[s,c]of[[n,r.value],[i,o]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=iI(d[0]);!l||a.has(l)||(a.add(l),t.push({field:r.field,value:l}))}}}return t}async function aI(e,t,n=t){let i=Pe.isAbsolute(e)?Pe.resolve(e):Pe.resolve(n,e),r;try{r=await Nh.stat(i)}catch{return}if(!r.isFile())return;let[a,o]=await Promise.all([ma(t),ma(i)]);if(me(a,o)){let s=Pe.relative(a,o);return!s||s.startsWith("..")||Pe.isAbsolute(s)?void 0:{path:Ms(s),scope:"project"}}return{path:Ms(i),scope:"global"}}async function oI(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>$n(c,t))),r=new Map,a=rI(nI(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await aI(c,t,n))}));let s=a.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of s){if(!d)continue;let l=$n(d,t),u=r.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,r.set(l,u)}return[...r.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:i.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 Mh(e,t,n){let i=await la(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ua(i,"files")}async function sI(e,t){let n=await ma(t),i=await Promise.all(e.map(async a=>{let o=a.trim();if(!o)throw new g("Files lookup paths must not be empty.",y.USAGE);if(!Pe.isAbsolute(o))return _t(o);let s=await ma(o);return me(n,s)?_t(Pe.relative(n,s)):_t(s)})),r=[...new Set(i)].sort((a,o)=>a.localeCompare(o));if(r.length===0)throw new g("Files lookup requires at least one path.",y.USAGE);return r}function cI(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new g(`Files lookup ${i} must be a non-negative integer.`,y.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 jh(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 i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function dI(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,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(Fh)}async function lI(e){if(e.explain)return uu({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 uI(e){if([e.strictRead,e.noTruncate,e.explain,cd()].includes(!0))return null;let t=await mr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?il({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function mI(e){let t=[],n=await pr(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=dI({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&r.length>0)throw new g(`Files lookup could not read every item: ${r.join("; ")}`,y.GENERIC_FAILURE);let a=await lI({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),o=(a?[...i].sort((s,c)=>{let d=a.explanations.get(c.item.id).score-a.explanations.get(s.item.id).score;return d!==0?d:Fh(s,c)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:o.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+o.length<i.length,truncated:e.offset+o.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:o.map(s=>({item:jh(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function jF(e,t){let n=M(process.cwd(),t.path),i=Ge(n);await te(n);let r=await sI(e.paths,i);if(e.lineRange&&r.length!==1)throw new g("Files lookup line attribution requires exactly one source path.",y.USAGE);let a=await T(n),o=H(a,F()),{offset:s,limit:c}=cI(e),d=await uI({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:r,total:d.total,count:d.matches.length,offset:s,limit:c,has_more:s+d.matches.length<d.total,truncated:s+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:jh(l.item),files:l.files}))}:mI({pmRoot:n,settings:a,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function FF(e,t,n){let i=M(process.cwd(),n.path),r=Ge(i);await te(i);let a=await T(i),o=H(a,F()),s=await ge(i,e,a.id_prefix,a.item_format,o.type_to_folder);if(!s)throw new g(`Item ${e} not found`,y.NOT_FOUND);let c=await ye(s,{schema:a.schema}),d=await oI(c.document,r,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let b=c.document.metadata.files??[];return{id:s.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=z(t.author,a.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],w=new Set,v=await at({pmRoot:i,settings:a,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let O=[...b.metadata.files??[]],P=new Set(O.map(Se=>$n(Se,r)));_=[],w.clear();for(let[Se,_e]of h.entries()){let pe=$n(_e,r);P.has(pe)||(O.push(_e),P.add(pe),_.push(_e),w.add(Se))}let x=Ns(O),q=t.appendStable?x:Ls(x);return q.length>0?b.metadata.files=q:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==h.length?[`files_discover_skipped_existing:${h.length-_.length}`]:[]}}}),E=v.item.files??[],k=new Set(_.map(b=>$n(b,r))),I=E.filter(b=>k.has($n(b,r))),C=l.filter((b,O)=>!w.has(O)),S=[...u,...C];return{id:v.item.id,files:E,changed:I.length>0,apply:!0,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:I.length,skipped_existing_count:S.length,candidates:d,added:I,skipped_existing:S}}import{readFileSync as pI}from"node:fs";import fa 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]="597a781e-a00d-5083-8d57-3fae870f9ccd")}catch{}})();var fI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),js=new Set(["--pm-path","--path","--author"]),hI={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"])},_I=new Set(["-p","--package"]),gI=new Set(["-c","--call"]),yI=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),wI=new Set(["-C","--prefix","--userconfig","--cache"]),WF=new Set(["--cwd"]),qF=new Set(["--cwd"]),vI=new Set(["exec","x"]),GF=new Set(["run","run-script"]),BF=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function bI(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function kI(e,t=process.cwd()){let n=EI(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[i,...r]=n;if(Uh(i)||Hh(i,t))return r;if(i==="node"&&r[0]&&Hh(r[0],t))return r.slice(1);let a=i==="npx"||i==="bunx"?Fs(r):i==="pnpm"?II(r):i==="npm"?RI(r):null;return a&&(Uh(a.command)||xI(a.command))?a.args:null}var zh=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let s of bI(a)){let c=kI(s),d=c?AI(c):null,l=d&&fI.has(d.subcommand)?CI(d.remaining,hI[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(l)}return[...o].sort((s,c)=>s.localeCompare(c))};function EI(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 JF(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(js.has(n)){t+=2;continue}t+=1;continue}return n}}function Uh(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function SI(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function xI(e){let t=SI(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Hh(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 i=fa.resolve(t,e);try{return JSON.parse(pI(fa.join(fa.dirname(fa.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Fs(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let a=r[1];return a?{command:a,args:e.slice(t+1)}:null}if(gI.has(i)){t+=1;break}t+=_I.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Wh(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function II(e){let t=Wh(e,yI);return t?.subcommand!=="dlx"?null:Fs(t.args)}function RI(e){let t=Wh(e,wI);return!t||!vI.has(t.subcommand)?null:Fs(t.args)}function AI(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(js.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function CI(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(js.has(i)||t.has(i))&&(n+=1)}}import{execFile as TI}from"node:child_process";import{readFile as $I}from"node:fs/promises";import Gh from"node:path";import{promisify as DI}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 OI=DI(TI),Us=1,PI="linked-test-trust.json";function Hs(e){return Gh.join(Dc(e),PI)}function qh(){return{version:Us,acknowledged:{}}}async function zs(e){try{let t=JSON.parse(await $I(Hs(e),"utf8"));return t.version!==Us||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?qh():{version:Us,acknowledged:t.acknowledged}}catch{return qh()}}async function Ws(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 OI("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),i=n.trim();return i.length===0?void 0:i}catch{return}}function qs(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function LI(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&ud(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Ii(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function NI(e,t,n,i){return e?.map(r=>r.command&&!r.provenance?{...r,provenance:{author:t,created_at:n,source_kind:"local_mutation",...i?{source_ref:i}:{}}}:r)}async function rU(e,t,n){if(!e||e.length===0)return e;for(let r of e)Sd(r);let i=qs();return NI(e,t,n,await Ws(i))}function Bh(e){return xe(A({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 aU(e,t,n){let i=await zs(e);return Jh(t,n,i)}function Jh(e,t,n){let i=Bh(e),r=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:i,trusted:!0,reason:"legacy"};let a=Object.hasOwn(n.acknowledged,i);return e.provenance_invalid===!0||!LI(e.provenance)?a?{fingerprint:i,trusted:!0,reason:"acknowledged",...Ii(void 0,t)}:{fingerprint:i,trusted:!1,reason:"invalid_provenance",...Ii(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r===void 0?{fingerprint:i,trusted:!0,reason:"local_mutation",...Ii(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r!==void 0&&r===t?{fingerprint:i,trusted:!0,reason:"local_source_ref",source_ref:r,current_source_ref:t}:a?{fingerprint:i,trusted:!0,reason:"acknowledged",...Ii(r,t)}:{fingerprint:i,trusted:!1,reason:"foreign_source_ref",...Ii(r,t)}}async function Vh(e,t,n){let i=await zs(e);return t.map(r=>Jh(r,n,i))}async function oU(e,t,n){let i=await zs(e),r=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(Bh);for(let a of r)i.acknowledged[a]={acknowledged_at:n};return await Mn(Gh.dirname(Hs(e))),await Z(Hs(e),`${JSON.stringify(i,null,2)}
|
|
57
|
-
`),{acknowledged:r.length,fingerprints: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]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function ha(e){return e.includeBody?rt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):pr(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 MI=5;async function jI(e,t){let n=t.hashMismatches.filter(a=>a!==ae);if(n.length===0)return;let i=await T(e),r=H(i,F());for(let a of n){let o=await re(e,a,i.locks.ttl_seconds,"history-drift-read",!1,!0,i.locks.wait_ms);try{let s=await ge(e,a,i.id_prefix,i.item_format,r.type_to_folder);if(s===null)throw new g(`Item ${a} not found`,y.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await ye(s,{schema:i.schema});if(c.metadata.id!==a)throw new g(`Item identity changed while validating ${a}`,y.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await Yu(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==a),...d[u].filter(m=>m===a)].sort((m,f)=>m.localeCompare(f));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==a),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===a)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function _a(e,t,n){let i=await Ut(e,t);await jI(e,i);let r=[["validate_history_drift_missing_streams",i.missingStreams.length],["validate_history_drift_unreadable_streams",i.unreadableStreams.length],["validate_history_drift_hash_mismatches",i.hashMismatches.length],["validate_history_drift_chain_mismatches",i.chainMismatches.length],["validate_history_drift_version_skews",i.versionSkews.length],["validate_history_drift_workspace_state_mismatches",i.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",i.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",i.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),a=n?Number.POSITIVE_INFINITY:MI,o=i.driftedItems.slice(0,a),s=i.identityDiscontinuities??[];return{check:{name:"history_drift",status:s.length>0?"error":r.length===0?"ok":"warn",ok:s.length===0&&r.length===0,details:{identity_discontinuities:s.slice(0,a),identity_discontinuities_count:s.length,identity_discontinuities_truncated:s.length>a,checked_items:t.length,drifted_items_count:i.driftedItems.length,drifted_items:o,drifted_items_truncated:o.length<i.driftedItems.length,counts:{missing_streams:i.missingStreams.length,unreadable_streams:i.unreadableStreams.length,hash_mismatches:i.hashMismatches.length,chain_mismatches:i.chainMismatches.length,version_skews:i.versionSkews.length,workspace_state_mismatches:i.workspaceStateMismatches.length,workspace_state_missing:i.workspaceStateMissing.length,workspace_state_unreadable:i.workspaceStateUnreadable.length},workspace_state_mismatches:i.workspaceStateMismatches,workspace_state_missing:i.workspaceStateMissing,workspace_state_unreadable:i.workspaceStateUnreadable,version_skews:i.versionSkews.slice(0,a)}},warnings: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]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function ga(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],a=new Set([n]),o=s=>{for(let c of(t.get(s)??[]).filter(d=>i.has(d))){if(c===n&&r.length>1)return r.push(n),!0;if(!a.has(c)){if(a.add(c),r.push(c),o(c))return!0;r.pop(),a.delete(c)}}return!1};return o(n)?[...r]:[...e,n]}function FI(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function UI(e,t,n,i){for(let r of e.dependencies??[]){if(typeof r!="object"||r===null||typeof r.id!="string")continue;let a=i.resolve(r.kind);if(!a?.hierarchy)continue;let o=n.get(r.id.toLowerCase());o&&(a.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function Gs(e,t=Gn()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),i=new Map(e.map(r=>[r.id,[]]));for(let r of[...e].sort((a,o)=>a.id.localeCompare(o.id))){let a=i.get(r.id),o=FI(r.parent,n);o&&a.push(o),UI(r,i,n,t)}for(let[r,a]of i)i.set(r,[...new Set(a)].sort());return i}function Bs(e,t,n=Gn()){let i=hr(e,o=>t?ed(o,t):o==="closed"||o==="canceled",n),r=Gs(e,n),a=i.cycles.map(o=>o.item_ids);return{cycle_count:a.length,active_cycle_count:i.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:i.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(a.flat())].sort(),cycle_sample_paths:a.map(o=>ga(o,r).join("->")),cardinality_violation_count:i.cardinality_violations.length,active_cardinality_violation_count:i.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:i.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:i.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:i.divergences.length,active_parent_divergence_count:i.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:i.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:i.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 $t(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Js(e){return $t(e).replace(/\/+$/,"")}function ze(e){let t=Y(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Vs(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]="9ef196b2-3eef-5bac-b949-bcb3e947c44d")}catch{}})();var qI=["src","tests","docs"],GI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],BI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),JI=["resolution","expected_result","actual_result"],VI=["default","tracked-all","tracked-all-strict"],Kh=["core","strict","custom"],va=["off","warn","error"],Xs=["author","acceptance_criteria","estimated_minutes","close_reason"],Zh=[...Xs,"reviewer","risk","confidence","sprint","release"],Zs=Array.from(new Set(Zh)),KI={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"},YI={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"},XI={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"},ZI={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"},QI={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"},eR=32*1024*1024,tR=1e4,Qs=40,We=5,nR=4096,iR=255,rR=WI(zI);function Qh(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||i===!1&&n.endsWith("_truncated")||(t[n]=typeof i=="object"&&i!==null?Qh(i):i);return t}function aR(e){return{...e,checks:e.checks.map(t=>({...t,details:Qh(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 ka(e,t){return er(e,t)??e}function Ri(e,t){return t.terminal_statuses.has(ka(e,t))}function Dt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ya(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function oR(e){let t=Dt(Ec),n={blocked_reason:Dt(Mi.blocked_reason),resolution:Dt(Mi.resolution),actual_result:Dt(Mi.actual_result)},i=Dt(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:Dt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Dt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Dt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:ya(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:ya(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ya(r.resolution,n.resolution)?"default":"settings",actual_result:ya(r.actual_result,n.actual_result)?"default":"settings"}}}function e_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Kh.includes(t))return t;throw new g(`Unknown --metadata-profile value "${e}". Supported values: ${Kh.join(", ")}.`,y.USAGE)}function t_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(va.includes(t))return t;throw new g(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${va.join(", ")}.`,y.USAGE)}function n_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(va.includes(t))return t;throw new g(`Unknown --parent-cycle-severity value "${e}". Supported values: ${va.join(", ")}.`,y.USAGE)}function sR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>KI[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function cR(e,t,n){let i=sR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Xs],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Zh],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Xs],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var dR=new Set(["acceptance_criteria","estimated_minutes"]);function i_(e,t,n,i){return!i&&dR.has(t)&&Ri(e.status,n)?!1:t==="author"?!Y(e.author):t==="acceptance_criteria"?!Y(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?ka(e.status,n)===n.close_status&&!Y(e.close_reason):t==="reviewer"?!Y(e.reviewer):t==="risk"?!Y(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!Y(e.confidence):t==="sprint"?!Y(e.sprint):!Y(e.release)}function r_(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 g(`Unknown --scan-mode value "${e}". Supported values: ${VI.join(", ")}.`,y.USAGE)}function a_(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ee.resolve(t);let n=Ee.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ee.dirname(Ee.dirname(n));let i=Ee.resolve(process.cwd()),r=Yh(n),a=Yh(i),o=Ee.relative(r,a);return o.length===0||!o.startsWith("..")&&!Ee.isAbsolute(o)?n:i}function Yh(e){try{return HI.native(e)}catch{return Ee.resolve(e)}}function lR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function ic(e,t,n){let i=t.length>0?Ee.join(e,t):e,r;try{r=await nc.readdir(i,{withFileTypes:!0})}catch(a){if(j(a))return;throw a}for(let a of r){if(a.name.startsWith("."))continue;let o=t.length>0?Ee.join(t,a.name):a.name;if(a.isDirectory()){if(BI.has(a.name))continue;await ic(e,o,n);continue}a.isFile()&&n.push($t(o))}}async function ec(e){let t=[];for(let n of qI)await ic(e,n,t);for(let n of GI){let i=Ee.join(e,n);try{(await nc.stat(i)).isFile()&&t.push($t(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function o_(e){try{let{stdout:t}=await rR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:eR,windowsHide:!0,timeout:tR}),n=t.split("\0").map(i=>$t(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function uR(e,t){let n=new Set,i=Js(vc);i.length>0&&n.add(i);let r=Js(Ee.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((a,o)=>a.localeCompare(o))}function Xh(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function mR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await o_(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await ec(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await ec(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ee(e,t=We){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function qt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ee(e,Qs);return{values:n.values,truncated:n.truncated,total:e.length}}var pR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},fR={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function hR(e){let t=e.missing_fields.map(n=>`${pR[n]} "${fR[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function s_(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):tm(t);if(r.length===0)return;let a=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...a?{fix_hints_truncated:!0}:{}}}function c_(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 _R="validate_metadata_duplicate_issue_codes";function d_(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:We,i=e.slice(0,n);return{rows:i.map(r=>({code:r.code,count:r.count,ids:r.ids,titles:r.titles,remediation_hint:`Items ${r.ids.join(", ")} share issue code "${r.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${_R}:${e.length}`]}}function gR(e,t,n){let i=Object.fromEntries(Zs.map(r=>[r,[]]));for(let r of e)for(let a of Zs)i_(r,a,t,n)&&i[a].push(r.id);return i}function yR(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let a=t[r];a.length>0&&i.push(`${YI[r]}:${a.length}`)}return i.push(...n),i}function l_(e,t){let n={};for(let i of e.required_fields){let r=t[i],a=r?r.length:0,o=XI[i];n[o]=a}return n}function u_(e,t,n){let i=[];for(let r of e.required_fields){let a=t[r];if(a)for(let o of a){let s=n.get(o)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";i.push({item_type:c,field:r})}}return i}function wR(e,t,n,i){for(let r of t.required_fields){let a=n[r];if(!a||a.length===0)continue;let o=ZI[r],s=QI[r];if(!o||!s)continue;let c=ee(a,i?a.length:We);e[o]=c.values,e[s]=c.truncated}}function m_(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:Y(n.get(r)?.resolution)})):[]}function p_(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:Y(n.get(r)?.type)})):[]}function vR(e,t,n,i,r){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=gR(e,n,o),c=Ah(e,{configuredPrefixes:r}),d=d_(c,i),l=yR(t,s,d.warnings),u=l_(t,s),m=u_(t,s,a),f=Ch(m),p={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:[...Zs],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),wR(p,t,s,i);let h=m_(t,s,a),_=p_(t,s,a);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:_}}function bR(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(ka(m.status,t))),a=[],o=[];for(let m of r){let f=JI.filter(p=>!Y(m[p]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:Y(m.close_reason)}))}let s=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:We,d=ee(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=a.map(m=>hR(m)),u=ee(l,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_closed_items:r.length,missing_resolution_items:a.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:s,resolutionBackfillRows:o}}function f_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function h_(e,t="pm",n=Ic()){let i=new Set(e.map(a=>a.id)),r=[...e].sort((a,o)=>a.id.localeCompare(o.id));return new Map(r.map(a=>{let o=new Set,s=ze(a.blocked_by);s&&i.has(s)&&o.add(s),(a.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&&i.has(d)).forEach(d=>o.add(d));let c=ze(a.definition_of_ready);return g_(c??"",t).filter(d=>i.has(d)).forEach(d=>o.add(d)),[a.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function __(e,t,n){let i=Sl(e,n?l=>Ri(l,n):void 0),r=i.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),a=i.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:We,s=ee(r,o),c=ee(a,o),d=ee(i.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:r.length===0?"ok":"warn",ok:r.length===0,details:{checked_items:e.length,dangling_reference_count:r.length+a.length,active_dangling_reference_count:r.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.truncated,legacy_terminal_dangling_reference_count:a.length,legacy_closed_dangling_reference_count:i.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:i.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function g_(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${f_(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,a)=>r.localeCompare(a))}function y_(e){let t=0,n=new Map,i=new Map,r=[],a=new Set,o=[],s=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),a.add(d);for(let u of e.get(d)??[])n.has(u)?a.has(u)&&i.set(d,Math.min(i.get(d),n.get(u))):(s(u),i.set(d,Math.min(i.get(d),i.get(u))));if(i.get(d)!==n.get(d))return;let l=[];for(;r.length>0;){let u=r.pop();if(a.delete(u),l.push(u),u===d)break}l.sort((u,m)=>u.localeCompare(m)),o.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||s(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 w_(e,t="pm"){let n=h_(e,t),i=y_(n),r=[...new Set(i.flat())].sort((o,s)=>o.localeCompare(s)),a=i.map(o=>ga(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:a}}function v_(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 ba(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function b_(e,t){let n=ba(e).split("/").filter(Boolean),i=ba(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function kR(e,t){let n=ba(t),i=ba(e),r=t.endsWith("/")?t:`${t}/`,a=e.startsWith(r),o=n.length>0&&n===i,s=b_(e,t);return!a&&!o&&s===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function ER(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function SR(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(a=>(i==="docs"?a.docs??[]:a.files??[]).map(o=>({item:a,link:o}))).forEach(({item:a,link:o})=>{if(o.scope!=="project")return;let s=$t(o.path);if(s.length===0||s===e)return;let c=kR(e,s);c!==null&&ER(r,a,c.score)&&(r={item:a,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function k_(e,t){return e.map(n=>{let i=v_(n),r=i==="docs_unowned"?"docs":"files",a=SR(n,i,t),o=a?.id??"<id>";return{path:n,classification:i,owner_candidate:a,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function E_(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function xR(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=ze(e[n]);return r?i.some(a=>r.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function IR(e,t,n,i,r){let a=ze(t.parent),o=a?n.get(i.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Ri(o.status,r)}}function RR(e,t,n,i){let r=ze(e.blocked_by),a=ze(e.blocked_reason),o=a?.toLowerCase(),s=ka(e.status,n),c=[];return t.has(s)?(!r&&!a&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function AR(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Ri(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=xR(c,i);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=ze(c.parent),u=l?r.get(a.get(l.toLowerCase())??l):void 0;if(u&&Ri(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(IR(c,u,r,a,n))),t){let m=RR(c,o,n,i);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function CR(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 wa(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Ks(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function TR(e,t,n,i,r){let a=[];e.closureLikeRows.length>0&&a.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&a.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&a.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=wa("validate_lifecycle_dependency_cycles",n,r.dependencyCycles),s=wa("validate_hierarchy_parent_cycle",i,r.activeHierarchyCycles),c=wa("validate_hierarchy_cardinality_violation",i,r.activeHierarchyCardinality),d=wa("validate_hierarchy_parent_divergence",i,r.activeHierarchyDivergence),l=Ks("validate_legacy_hierarchy_parent_cycle",i,r.legacyHierarchyCycles),u=Ks("validate_legacy_hierarchy_cardinality_violation",i,r.legacyHierarchyCardinality),m=Ks("validate_legacy_hierarchy_parent_divergence",i,r.legacyHierarchyDivergence);return[...a,...o?[o]:[],...s?[s]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function S_(e){let t=$t(e);return t.length>nR||t.split(/[\\/]/).some(n=>n.length>iR)}async function $R(e,t){let n=Ee.isAbsolute(t)?t:Ee.resolve(e,t);if(S_(n))return!1;try{let i=await nc.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return lR(i,["ENOENT","ENOTDIR"])}}async function DR(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(a=>({item:r,artifact:a,link_kind:"files"})),...(r.docs??[]).map(a=>({item:r,artifact:a,link_kind:"docs"}))]);for(let{item:r,artifact:a,link_kind:o}of i){if(a.scope!=="project")continue;if(Si(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=$t(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await $R(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:r.id,path:s,link_kind:o})))}return n}function OR(e,t,n,i,r,a){let o=i==="tracked-all-strict",s=o&&!r,c=r||o,d=c?[]:uR(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>Xh(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Xh(f,d)),m={};if(l.length>0){let f=qt(l,a);m.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function x_(e,t,n,i,r,a,o,s="pm"){let c=AR(e,t,r,a);CR(c);let d=w_(c.activeItems,s),l=Bs(e,r),u=Rr(r,e,o?Number.POSITIVE_INFINITY:We),m=[...TR(c,t,n,i,{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}),...Ar(u)],f=o?Number.POSITIVE_INFINITY:We,p=ee(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=ee(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),_=ee(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),w=ee(d.cycle_item_ids,f),v=ee(d.cycle_sample_paths,f),E=ee(l.cycle_item_ids,f),k=ee(l.cycle_sample_paths,f),I=ee(l.cardinality_violation_rows,f),C=ee(l.parent_divergence_rows,f),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&i==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.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:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:_.values,stale_blocker_rows_truncated:_.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:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:i,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:E.values,parent_cycle_item_ids_truncated:E.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.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:I.values,hierarchy_cardinality_violation_rows_truncated:I.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:C.values,hierarchy_parent_divergence_rows_truncated:C.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function I_(e,t,n,i,r,a,o=fe(Sc.schema)){let s=await DR(e,t),c=new Map(e.map(x=>[x.id,x])),d=[...new Set(s.missingLinkedPaths)].sort((x,q)=>x.localeCompare(q)),l=await mR(t,i),u=OR(l,n,t,i,r,a),m=u.candidateFiles.filter(x=>!s.linkedProjectPaths.has(x)),f=k_(m,e),p=$h(d,u.candidateFiles),h=new Map(p.map(x=>[x.path,x.classification])),_=p.filter(x=>x.classification==="moved").length,w=s.staleLinkRows.map(x=>({...x,classification:h.get(x.path)??"deleted"})).sort((x,q)=>x.item_id.localeCompare(q.item_id)||x.path.localeCompare(q.path)||x.link_kind.localeCompare(q.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let E=[...s.remoteLinkedPaths].sort((x,q)=>x.localeCompare(q)),k=qt(E,a),I=qt(d,a),C=qt(m,a),S=qt(f.map(x=>`${x.path}:${x.classification}:owner_candidate=${x.owner_candidate?.id??"unowned"}`),a),b=a?f:qt(E_(f),!1).values,O=qt(Dh(p),a),P=_h(w,p,x=>c.get(x),o,a?1/0:Qs);return P.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${P.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.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:a?"full":"summary",file_list_summary_limit:Qs,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:r,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:s.linkedProjectPaths.size,remote_linked_paths_count:E.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.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:I.total,missing_linked_paths:I.values,missing_linked_paths_truncated:I.truncated,missing_linked_paths_moved_count:_,missing_linked_paths_deleted_count:p.filter(x=>x.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(x=>x.classification==="malformed").length,missing_linked_path_classifications:O.values,missing_linked_path_classifications_truncated:O.truncated,...P,orphaned_paths_count:m.length,orphaned_paths_total:C.total,orphaned_paths:C.values,orphaned_paths_truncated:C.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function PR(e,t){let n=[];return e.forEach(({item:i,linkedTest:r},a)=>{let o=t[a];if(o.trusted)return;let s=Vs(r.command??"");n.push(`${i.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function R_(e,t,n,i){let r=new Set(e.map(I=>I.id.toLowerCase())),a=0,o=0,s=new Set,c=[],d=e.flatMap(I=>(I.tests??[]).map(C=>({item:I,linkedTest:C}))),l=await Ws(qs()),u=await Vh(i,d.map(({linkedTest:I})=>I),l),m=PR(d,u);for(let{item:I,linkedTest:C}of d){if(typeof C.command!="string"||C.command.trim().length===0)continue;a+=1;let S=zh(C.command,t);if(S.length!==0){o+=S.length;for(let b of S)s.add(b),r.has(b.toLowerCase())||c.push(`${I.id}:${b}:${Vs(C.command)}`)}}let f=[...new Set(c)].sort((I,C)=>I.localeCompare(C)),p=[...new Set(f.map(I=>I.split(":")[1]??""))].filter(I=>I.length>0).sort((I,C)=>I.localeCompare(C)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let _=n?Number.POSITIVE_INFINITY:We,w=ee(f,_),v=ee(p,_),E=ee([...s].sort((I,C)=>I.localeCompare(C)),_),k=ee(m,_);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:a,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:E.values,unique_referenced_pm_ids_truncated:E.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:k.values,untrusted_linked_tests_truncated:k.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function LR(e,t){let n=Qi(e.map(c=>({ref:c.id,version:Zi(c)})),Hn,Xi),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:We,a=ee(n.outdated,r),o=ee(n.ahead,r),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:Hn,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var tc="pm validate auto-fix";async function A_(e,t,n){switch(e.kind){case"set_closed_at":await ph(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:tc};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new g("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",y.USAGE);await n.runUpdate(e.item_id,i,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 Ys(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function C_(e,t,n){let i=[],r=[],a=new Map;for(let o of e.filter(s=>Ys(s)===null))try{await A_(o,t,n),i.push(o)}catch(s){r.push({fix:o,error:s})}for(let o of e.filter(s=>Ys(s)!==null)){let s=Ys(o),c=a.get(s);c?c.push(o):a.set(s,[o])}for(let o of a.values()){let s=o[0];if(!s)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{s.kind==="prune_file_link"?await Mh(s.item_id,{remove:c,message:tc},t):await Lh(s.item_id,{remove:c,message:tc},t),i.push(...o)}catch(d){r.push(...o.map(l=>({fix:l,error:d})))}}return{applied:i,failed:r}}var gH={applyValidateFix:A_,applyValidateFixes:C_,attachValidateFixHints:s_,buildCommandReferencesCheck:R_,buildDependencyReferencesCheck:__,buildCloseReasonBackfillRows:m_,buildFilesCheck:I_,buildLifecycleCheck:x_,buildLifecycleDependencyGraph:h_,buildLifecycleParentGraph:Gs,buildEstimateBackfillRows:p_,buildMetadataCounts:l_,buildMissingFieldOccurrences:u_,buildOrphanedPathRows:k_,classifyOrphanedPath:v_,collectDefaultProjectFileCandidates:ec,collectTrackedGitFileCandidates:o_,detectLifecycleDependencyCycles:w_,detectLifecycleParentCycles:Bs,escapeRegExp:f_,extractItemIds:g_,findLifecycleDependencyCycleComponents:y_,isMetadataFieldMissing:i_,linkedArtifactPathExceedsFilesystemLimits:S_,listFilesRecursive:ic,resolveDependencyCycleSeverity:t_,resolveParentCycleSeverity:n_,resolveFileScanMode:r_,resolveLifecycleDependencyCycleSamplePath:ga,resolveRequestedChecks:c_,resolveValidateMetadataProfile:e_,resolveWorkspaceRoot:a_,sharedDirectoryPrefixLength:b_,summarizeOrphanedPathRows:E_,summarizeDuplicateIssueCodes:d_,toMeaningfulString:ze};function NR(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function MR(e,t,n,i){let r=await yh(e,new Set(t.map(_=>_.id)),n,{schema:i.schema,extensionFieldNames:Gt(F())}),a=[];r.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=a.length,s=await Kr(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await cn(e,sn(i));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Et(e),l=d===null?null:await dn(d);l!==null&&l.status!=="ok"&&a.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await pt(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Rn(m);f.length>0&&a.push(`validate_merge_decisions_unreviewed:${f.length}`),NR(a,u.invalid_evidence_count);let h=o>0?"error":a.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...r,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),lossless_merge_receipt_count:p.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(p.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:a}}function et(e,t,n){n&&s_(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function jR(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let r=await Xl(e.pmRoot,e.items,i?1/0:We,e.sourceIncomplete);et(t,r,n)}if(e.requestedChecks.has("metadata")){let r=vR(e.items,e.metadataPolicy,e.statusRegistry,i,[e.settings.id_prefix]);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows;let a=await mh(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,i?1/0:We);t.closureTimestampFixes=a.fixes,Object.assign(r.check.details,a.details),r.warnings.push(...a.warnings),r.check.ok=r.warnings.length===0,r.check.status=r.check.ok?"ok":"warn",et(t,r,n)}if(e.requestedChecks.has("resolution")){let r=bR(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,et(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=x_(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,et(t,r,n),et(t,__(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await I_(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=r.staleLinkPruneRows,et(t,r,n)}return e.requestedChecks.has("command_references")&&et(t,await R_(e.items,e.settings.id_prefix,i,e.pmRoot),n),e.requestedChecks.has("history_drift")&&et(t,await _a(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&et(t,LR(e.items,i),n),e.requestedChecks.has("storage_integrity")&&et(t,await MR(e.pmRoot,e.items,H(e.settings,F()).type_to_folder,e.settings),n),t}function FR(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...t.closureTimestampFixes),i.push(...bh(t.closeReasonBackfillRows)),i.push(...vh(t.resolutionBackfillRows)),i.push(...kh(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...Eh(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Sh(t.staleLinkPruneRows)),i}async function UR(e,t,n,i,r,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=FR(e,t,n),{applicable:s,gated:c}=Ih(o,i),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await C_(s,r,a);l.push(...m.applied.map(Ei)),u.push(...m.failed.map(({fix:f,error:p})=>({...Ei(f),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(Ei),applied_fixes:l,gated_fixes:c.map(m=>({...Ei(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function T_(e,t,n={}){dd(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new g("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",y.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new g("--fix-scope requires --auto-fix.",y.USAGE);let r=xh(e.fixScope),a=M(process.cwd(),t.path);await te(a);let o=await T(a),s=fe(o.schema),c=H(o,F()),d=c_(e),l=[],u=await ha({includeBody:["history_drift","metadata","completeness"].some(O=>d.has(O)),pmRoot:a,settings:o,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let O=await Qn(a);O.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${O.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=e_(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=cR(p,f,o.validation.metadata_required_fields),_=oR(o),w=t_(e.dependencyCycleSeverity),v=n_(e.parentCycleSeverity),E=r_(e.scanMode),k=a_(a),I=await jR({requestedChecks:d,options:e,global:t,pmRoot:a,workspaceRoot:k,settings:o,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:_,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:E,initialWarnings:[...new Set(l)],sourceIncomplete:m}),C=i?await UR(e,I,o,r,t,n):void 0,S=[...new Set(I.warnings)].sort((O,P)=>O.localeCompare(P)),b={ok:!I.checks.some(O=>O.status==="error"),has_warnings:S.length>0,checks:I.checks,warnings:S,...C!==void 0?{fixes:C}:{},generated_at:$(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...aR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as HR}from"node:child_process";import{promisify as zR}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 WR=zR(HR),qR=16,GR=3e4;function BR(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(i=>typeof i=="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 JR(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let i=t.parameters??{},r=n.parameters??{};for(let a of Object.entries(r).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(i,a))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${a}`);for(let[a,o]of Object.entries(i)){let s=r[a];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${a}`);if(o===null||typeof o!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${a} must be ${s.type}`)}return{...i}}async function VR(e,t,n,i){let r=JR(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:r,trigger:i,pm_root:n,...sd(n)}));a.catch(()=>{});let o;try{let s=await Promise.race([a,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??GR),o.unref?.()})]);return BR(e,t.key,s)}finally{clearTimeout(o)}}function D_(e,t,n,i){let r=e;for(let a of t.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))throw new Ke(`assurance field ${t} is not present`,{source_kind:n,field:t,...i?{check:i}:{}});r=r[a]}if(typeof r=="number"&&Number.isFinite(r)||Array.isArray(r)&&r.every(a=>typeof a=="string"))return r;throw new Ke(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...i?{check:i}:{}})}function $_(e,t,n,i){let r=e.checks.find(a=>a.name===t);if(!r)throw new Ke(`assurance check ${t} is not present`,{source_kind:i,field:n,check:t});return{value:n==="status"||n==="ok"?r.ok?0:1:D_(r.details,n,i,t),population_size:1,cost:e.checks.length}}async function KR(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await WR("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function YR(e,t){let n=new Array(t.length),i=0,r=Array.from({length:Math.min(qR,t.length)},async()=>{for(;i<t.length;){let a=i;i+=1;let o=t[a],s=await nt(Ot(e,o.id),o.id);n[a]=s.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(r),n.flat()}async function Ai(e,t={}){let n=await T(e),i=H(n),r=fe(n.schema),a=(t.strict_read===!0?(await Il(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await rt(e,n.item_format,i.type_to_folder,void 0,n.schema)).map(m=>({...m,id:m.id,status:m.status,type:m.type})),o={path:e},s=F(),c=Object.fromEntries((s?.assurance_providers??[]).map(m=>[m.definition.id,{cost_class:m.runtime_definition.cost_class,network:m.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await KR(e,t.tree_id),items:a,history:t.include_history===!1?[]:await YR(e,a),terminal_statuses:[...r.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async m=>{if(m.kind==="graph"){let h=A({operation:m.operation,parameters:m.parameters??{}}),_=d.get(h);_===void 0&&(_=$l(m.operation,void 0,void 0,{...m.parameters,full:!0},o),d.set(h,_));let w=await _;return{value:D_(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){l??=T_({counts:!0},o);let h=await l;return $_(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=dh(o,{checkOnly:!0,full:!0});let h=await u;return $_(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=xd(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return VR(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as XR}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 O_(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:i,limit:r}=Ji({...t,change:{}});return{policy:n,...i===void 0?{}:{cursor:i},...r===void 0?{}:{limit:r},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function ZR(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 i=n;if(i.fingerprint!==t||typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return i.offset}function QR(e,t,n,i,r,a){let o=Object.fromEntries(Ha.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=XR("sha256").update(r);for(let f of i){let p=e.membership.get(f),h=n.has(f),_=p.family_ids.length>0;_&&h&&(s+=1),_||(c+=1),h||(d+=1);let w=t.get(f)?.escape_class;w!==void 0&&Ha.includes(w)&&(o[w]+=1,l+=1),m.update(A([f,h,t.get(f)??null,p.id,p.family_ids])),(!a||!_||!h)&&u.push(f)}return{classCounts:o,coveredCount:s,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function P_(e,t,n={}){vd(e);let i=n.limit??25;if(!Number.isSafeInteger(i)||i<1||i>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let r=new Set,a=new Map;for(let k of t){if(r.has(k.id))throw new TypeError(`Duplicate recurrence item ${k.id}`);r.add(k.id);let I=Bi(k);I!==void 0&&a.set(k.id,I)}let o=_d(e.families,a),s=[...o.membership.keys()].sort(),c=A({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:f,selected:p,fingerprint:h}=QR(o,a,r,s,c,n.uncoveredOnly===!0),_=ZR(n.cursor,h);if(_>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(_,_+i).map(k=>{let I=o.membership.get(k),C=r.has(k);return{item_id:k,lineage_id:I.id,lineage_item_count:I.item_ids.length,family_ids:I.family_ids,present:C,...C?I.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=_+w.length,E=s.length===0?null:d.production_defect/s.length;return{ok:u===0&&m===0,fingerprint:h,items:w,total:p.length,has_more:v<p.length,...v<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:s.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:f,unclassified_item_count:s.length-f,class_counts:d,escape_rate:f===s.length?E:null,escape_rate_lower_bound:E},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:i},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as eA}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 rc,L_=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],ac=["measurement","assertion","gate"];function tA(e){if(L_.includes(e))return e;throw Yi({command_path:"assurance",token:e,allowed:L_,display_name:"assurance action"})}function Dn(e,t,n){throw new g(t,y.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function nA(e){if(!e)return Dn("kind",`Assurance declaration kind is required. Expected: ${ac.join(", ")}`,"pm assurance list measurement");if(ac.includes(e))return e;throw new g(`Assurance declaration kind is required. Expected: ${ac.join(", ")}`,y.USAGE)}function N_(e){if(!e)return Dn("preset",`Assurance preset is required. Expected: ${ei.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(ei.includes(e))return e;throw new g(`Assurance preset is required. Expected: ${ei.join(", ")}`,y.USAGE)}function oc(e){return e.owner?.trim()?e.owner.trim():Dn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function iA(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(i){throw new g("assurance definition must be valid JSON",y.USAGE,{reason:i instanceof Error?i.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new g("assurance put requires a JSON object definition",y.USAGE);return n}async function rA(e){let[t,n,i]=await Promise.all([Kn(e,"measurement"),Kn(e,"assertion"),Kn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:i.items}}function M_(e,t){return t===!0?{id:e.id}:e}async function aA(e,t){let n=t.authorization_decision;if(!n)return[];let i=await Ai(e,{include_history:!1,resolve_tree:!1}),r=i.items.find(o=>o.id===n),a=new Set(i.terminal_statuses);if(!r||r.type.toLowerCase()!=="decision"||!a.has(r.status))throw new g(`Assurance authorization ${n} must name a terminal Decision item`,y.USAGE);return[r.id]}async function oA(e,t){let n=Ya(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>un))throw new g(`assurance verdict limit must be an integer from 1 through ${un}`,y.USAGE);let i=await Kl(t,{gate_id:e.id??e.gate,limit:n});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function j_(e,t,n){try{return await Qa(()=>Bl(e,t,n))}catch(i){if(!(i instanceof g)||i.context.reason!=="assurance_evaluation_refused")throw i;let r=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],a=le(r);throw Object.assign(i.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:[a],recovery:{next_best_command:a,suggested_retry:a,suggested_retry_args:r}}),i}}async function sA(e,t,n){if(e==="presets"){if(t.preset??t.id)return xr(N_(t.preset??t.id),oc(t));let r=ei.map(a=>{let o=xr(a,"pm-owner");return{id:a,title:o.title,description:o.description}});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return ln(()=>pu(n,N_(t.preset??t.id),oc(t),{author:t.author,message:t.message}));if(e==="derive"){let r=await fu(await Ai(n,{resolve_tree:!1,trigger:"derive"}),oc(t)),a=t.apply?await ln(()=>hu(n,r,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:r,count:r.length,...a?{applied:a}:{}}}if(!t.id)return Dn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new g("assurance promote requires --enforcement warn|block",y.USAGE);let i=await j_(n,"assertion",t.id);return ln(()=>_u(n,i,t.enforcement,{author:t.author,message:t.message}))}async function cA(e,t,n){if(!e.id)return Dn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let i=e.id;if(!e.trigger)throw new g("assurance run requires a trigger",y.USAGE);if(!jt.includes(e.trigger))throw new g(`Unknown assurance trigger ${e.trigger}. Expected: ${jt.join(", ")}`,y.USAGE);let r=e.trigger,[a,o]=await Promise.all([rA(t),Ai(t,{...n.workspace,tree_id:e.tree,trigger:r})]),s=await Qa(()=>ql(i,a,o,{trigger:r,dry_run:e.dry_run===!0}));return s.dry_run||await Vl(t,s,{author:e.author,message:e.message}),s}function F_(e){throw e instanceof g?e:new g(e instanceof Error?e.message:"assurance risk request is invalid",y.USAGE)}function dA(e){if(e.limit!==void 0)throw new g(`assurance ${e.action} does not accept --limit; set limit inside the definition`,y.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new g(`assurance ${e.action} definition must be valid JSON`,y.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?O_(t):Ji(t)}catch(n){if(e.action==="risk"&&n instanceof wd)throw new g(n.message,y.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 F_(n)}}function lA(e,t){let n=new Set;for(let[i,r]of t)e.item_fingerprints.get(i)!==r&&n.add(i);for(let i of e.item_fingerprints.keys())t.has(i)||n.add(i);return n}function uA(e,t,n){let i=A(t.policy),r=rc?.pm_root===e?rc:void 0,a=new Map(n.map(d=>[d.id,eA("sha256").update(A([hd(d),Bi(d)])).digest("hex")])),o=r?.policy_serialized===i?r:void 0,s=o?lA(o,a):new Set,c=gd(t.policy,o?n.filter(d=>s.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return rc={pm_root:e,policy_serialized:i,item_fingerprints:a,index:c},c}async function mA(e,t){let n=dA(e),i=await Ai(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?yd(uA(t,n,i.items),n.change,{cursor:n.cursor,limit:n.limit}):P_(n.policy,i.items,n)}catch(r){return F_(r)}}async function pA(e,t={},n={}){let i=tA(e.action),r=M(process.cwd(),t.path);if(i==="presets"||i==="apply"||i==="derive"||i==="promote")return sA(i,e,r);if(i==="verdicts")return oA(e,r);if(i==="run")return cA(e,r,n);if(["risk","lineages"].includes(i))return mA(e,r);let a=nA(e.kind);if(i==="list")return Kn(r,a);if(!e.id)return Dn("id",`assurance ${i} requires an id`,`pm assurance ${i} ${a} <id>`);let o=e.id;if(i==="show")return j_(r,a,o);if(i==="remove"){let l=await ln(()=>Jl(r,a,o,{author:e.author,message:e.message}));return M_(l,e.idOnly)}let s=iA(a,e.definition);if(s.id!==o)throw new g(`Assurance definition id ${s.id} does not match requested id ${o}`,y.USAGE);let c={author:e.author,message:e.message,...a==="assertion"?{authorized_decision_ids:await aA(r,s)}:{}},d=await ln(()=>kr(r,a,s,c));return M_(d,e.idOnly)}function ez(e,t,n){let i={...e,...t};return pA({action:Q(i,"subcommand")??Q(i,"assuranceAction")??Q(i,"operation")??"",kind:Q(i,"kind"),id:Q(i,"id"),definition:i.definition,trigger:Q(i,"trigger"),tree:Q(i,"treeId")??Q(i,"tree"),gate:Q(i,"gate"),limit:Ya(i.limit,"assurance verdict limit"),dry_run:i.dryRun===!0||i.dry_run===!0,fullChangedFields:i.fullChangedFields===!0,idOnly:i.idOnly===!0,author:Q(i,"author"),message:Q(i,"message"),preset:Q(i,"preset"),owner:Q(i,"owner"),apply:i.apply===!0,enforcement:Q(i,"enforcement")},n)}import On from"node:fs/promises";import Sa from"node:path";import Ea from"node:fs/promises";import sc 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 fA=864e5;function hA(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 _A(e,t){let n;try{n=await Ea.readdir(e,{withFileTypes:!0})}catch(r){if(j(r))return[];throw r}let i=[];for(let r of n)if(r.isDirectory()){let a=sc.join(e,r.name),o;try{o=await Ea.readdir(a)}catch(s){j(s)||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let s of o)s.endsWith(".json")&&i.push(`${r.name}/${s}`)}else r.name.endsWith(".json")&&i.push(r.name);return i.sort()}async function U_(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),a=Math.max(0,t.retentionDays)*fA,o=sc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await _A(o,s.warnings);for(let d of c){let l=sc.join(o,d),u=`checkpoints/${d}`;s.scanned+=1,i?.onRead&&s.warnings.push(...await i.onRead(l));let m;try{m=await Ea.readFile(l,"utf8")}catch(w){if(j(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=hA(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=r-p,_={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>a,reason:h>a?"expired":"active"};if(!_.stale){s.retained.push(u),s.entries.push(_);continue}if(!n){try{await Ea.unlink(l)}catch(w){if(!j(w)){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(_);continue}}i?.onWrite&&s.warnings.push(...await i.onWrite(l))}s.removed.push(u),s.entries.push(_)}return s}import cc from"node:fs/promises";import H_ 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]="9c0640f0-505c-5f4a-bb7a-daa3cc775239")}catch{}})();var gA=1440*60*1e3,yA=new Set(["committed","compensated"]);function wA(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:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function vA(e,t,n,i,r){let a=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(a))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=i-a;return yA.has(t)?o>r?{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 bA(e,t,n,i){let r=i.hooks?.onRead?await i.hooks.onRead(e):[],a=wA(await cc.readFile(e,"utf8")),o=vA(t,a.status,a.updatedAt,i.nowMs,i.retentionMs);return o.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),o.remove&&!i.dryRun&&(await cc.rm(e,{force:!0}),i.hooks?.onWrite&&r.push(...await i.hooks.onWrite(e))),{decision:o,warnings:r}}async function z_(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),a=Math.max(0,t.retentionDays)*gA,o=H_.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await cc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(j(d))return s;throw d}for(let d of c){let l=H_.join(o,d),u=`transactions/sdk/${d}`,m=await bA(l,u,d,{dryRun:n,hooks:i,nowMs:r,retentionMs:a});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.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]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var Ci=["index","embeddings","runtime","locks","checkpoints","transactions"],kA=1440*60*1e3,EA=[{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 SA(e,t,n){let i=t.relativePath,r=Sa.join(e,i),a=await Ne({path:r,scope:"project"});try{let o=await On.stat(r);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...a,`not_a_file:${i}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...a,`not_a_directory:${i}`]};if(n)return{removed:!0,warnings:a};t.kind==="file"?await On.unlink(r):await On.rm(r,{recursive:!0,force:!0});let s=await K({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...a,...s]}}catch(o){if(j(o))return{removed:!1,warnings:a};throw o}}async function xA(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],i=[],r=[],a=[],o=Date.now()-kA;for(let s of n){let c=Sa.join(e,s.relativePath);if(!await D(c))continue;let d=(await On.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=Sa.posix.join(s.relativePath,l),m=Sa.join(c,l);a.push(...await Ne({path:m,scope:"project"}));let f=await On.stat(m).catch(p=>{if(!j(p))throw p});if(f){if(f.mtimeMs>o){r.push(u);continue}i.push(u),!t&&(await On.rm(m,{recursive:!0,force:!0}),a.push(...await K({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:i,retained:r,warnings:a}}function IA(e){if(!e||e.length===0)return[...Ci];let t=e.flatMap(i=>i.split(",")).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);if(t.length===0)throw new g(`--scope requires at least one value (${Ci.join(",")})`,y.USAGE);let n=new Set;for(let i of t){if(!Ci.includes(i))throw new g(`Invalid --scope value "${i}". Expected one or more of: ${Ci.join(", ")}`,y.USAGE);n.add(i)}return Ci.filter(i=>n.has(i))}function RA(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"),i=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&i&&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(r=>r.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(r=>r.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 Ez(e,t={}){let n=M(process.cwd(),e.path);await te(n);let i=await T(n),r=t.dryRun===!0,a=IA(t.scope),o=EA.filter(p=>a.includes(p.scope)),s=[],c=[],d=[];for(let p of o){let h=await SA(n,p,r);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(a.includes("runtime")){let p=await xA(n,r);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(a.includes("locks")){let p=await em(n,{dryRun:r,hooks:{onRead:h=>Ne({path:h,scope:"project"}),onWrite:h=>K({path:h,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(a.includes("transactions")){let p=i.checkpoints.retention_days,h=await z_(n,{dryRun:r,retentionDays:p,hooks:{onRead:_=>Ne({path:_,scope:"project"}),onWrite:_=>K({path:_,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}let m;if(a.includes("checkpoints")){let p=i.checkpoints.retention_days,h=await U_(n,{dryRun:r,retentionDays:p,hooks:{onRead:_=>Ne({path:_,scope:"project"}),onWrite:_=>K({path:_,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}d.push(...await Gi({mode:r?"gc:dry-run":"gc",total_items:o.length}));let f=RA({dryRun:r,scopes:a,removed:s});return{ok:d.length===0,dry_run:r,scope:a,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:$()}}import{execFile as AA}from"node:child_process";import CA from"node:path";import{promisify as TA}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]="7fe99df0-8454-5667-9205-0b861ba212d1")}catch{}})();var $A=TA(AA),q_="@unbrained/pm-cli",DA="latest",OA={global:["--global"],project:[]};function W_(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new g('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"}function Ia(e){return e.trim().toLowerCase()}function G_(e,t){let n=Ia(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(i=>typeof i=="string"&&Ia(i)===n)}function PA(e,t){let n=M(process.cwd(),t.path),i=Jt(n,process.cwd());return{selected_root:e==="global"?i.global:i.project}}async function LA(e,t,n){try{let i=await $A(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:i.stdout,stderr:i.stderr}}catch(i){let r=typeof i=="object"&&i!==null&&"stderr"in i?String(i.stderr??""):"",a=r.trim().length>0?r.trim():i instanceof Error?i.message:String(i);throw new g(`Command failed: ${e} ${t.join(" ")}
|
|
58
|
-
${a}`,y.GENERIC_FAILURE)}}function Ra(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():DA}function xa(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():q_}async function NA(e,t){let n=e.commandRunner??LA,i=xa(e),r=Ra(e),a=`${i}@${r}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=Rc(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:i,target:a,command:o,before_version:s,...i===q_?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(o[0],o.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function MA(e){return CA.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function jA(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!MA(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function FA(e,t){let n=jA(e,t);return e.kind!=="local"||await D(n)?n:await D(e.location)?e.location:n}function UA(e,t,n,i){let r=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&i&&i.trim().length>0&&r.push("--ref",i.trim()),r}async function B_(e,t){let n=PA(e,t);return(await he(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function HA(e,t,n){let i=await B_(e,t);return i.find(r=>G_(r,n.name))??i.find(r=>Ia(r.directory)===Ia(n.directory))}async function zA(e,t,n,i,r){let a=Ra(t),o=await FA(e.source,a),s=UA(e.source,o,i,e.source.ref),c={name:e.name,directory:e.directory,scope:i,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(r)return c;try{await rs(o,{install:!0,project:i==="project",global:i==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await HA(i,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function WA(e,t,n,i){let r=[n?e.status:void 0,...t.map(a=>a.status)].filter(a=>typeof a=="string");return{requested_cli:n,requested_packages:i,planned:r.filter(a=>a==="planned").length,updated:r.filter(a=>a==="updated").length,skipped:r.filter(a=>a==="skipped").length,failed:r.filter(a=>a==="failed").length}}async function $z(e,t,n){let i=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...i?[i]:[],"--packages-only","--dry-run",...OA[W_(t)]];throw new g('Options "--cli-only" and "--packages-only" are mutually exclusive.',y.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:le(m),suggested_retry_args:m}})}let r=W_(t),a=t.dryRun===!0;if(t.cliOnly===!0&&i)throw new g('A package target cannot be used with "--cli-only".',y.USAGE);let o=!(t.packagesOnly===!0||i),s=t.cliOnly!==!0,c=o?await NA(t,a):{requested:!1,status:"skipped",package:xa(t),target:`${xa(t)}@${Ra(t)}`,command:["npm","install","-g",`${xa(t)}@${Ra(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await B_(r,n):[];if(i&&(d=d.filter(m=>G_(m,i)),d.length===0))throw new g(`Managed package "${i}" was not found in ${r} scope.`,y.NOT_FOUND);let l=[];for(let m of d)l.push(await zA(m,t,n,r,a));let u=WA(c,l,o,s);return{ok:u.failed===0,action:"upgrade",dry_run:a,scope:r,target:i,cli:c,packages:l,summary:u}}import{createHash as qA}from"node:crypto";import{isUtf8 as GA}from"node:buffer";import Ti from"node:fs/promises";import dc 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]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function J_(e){try{return(await Ti.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(j(t))return[];throw t}}function BA(e,t,n,i){let r=t.at(-1),a;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){a=t[c];break}let o=t[0]?.context?.history_compaction,s=typeof o=="object"&&o!==null&&"pruned_stream_digest"in o&&typeof o.pruned_stream_digest=="string"?o.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:n,stream_digest:i,latest_after_hash:r?.after_hash??null,latest_record_hash:r?.record_hash??null,latest_hash_algorithm:r?Re(r.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:s,last_maintenance:a?{op:a.op,ts:a.ts,record_hash:a.record_hash??null}:null}}function JA(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!GA(t))return null;let i=[];for(let r of t.toString("utf8").split(/\r?\n/u)){if(!r.trim())continue;let a=JSON.parse(r);if(typeof a!="object"||a===null||Array.isArray(a))return null;let o=a;if(![o.op,o.author,o.ts,o.before_hash,o.after_hash].every(s=>typeof s=="string")||!Array.isArray(o.patch))return null;i.push(o)}return Wn(i).ok?BA(e,i,t.length,n):null}catch{return null}}async function lc(e,t){if(!(await Ti.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=dc.join(e,"history"),i=await J_(n),r=new Map,a=[];for(let o of i){let s=o.slice(0,-6),c={id:s,digest:null,stream:null};a.push(c);let d=dc.join(n,o);try{let l=await Ti.lstat(d);if(r.set(o,A([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await Ti.readFile(d);c.digest=qA(t).update(u).digest("hex"),c.stream=JA(s,u,c.digest)}catch{}}if(A(i)!==A(await J_(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of r){let c=await Ti.lstat(dc.join(n,o));if(s!==A([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}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]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function uc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Pn(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function VA(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:Pn(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||Pn(e.latest_record_hash,e.latest_hash_algorithm))}function KA(e){return e===null?!0:!uc(e)||!mc(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&wt(e.ts)&&(e.record_hash===null||Pn(e.record_hash,"sha256")||Pn(e.record_hash,"sha512"))}function YA(e,t){return!uc(e)||!mc(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&Pn(e.stream_digest,t)&&VA(e)&&(e.checkpoint_digest===null||Pn(e.checkpoint_digest,"sha256"))&&KA(e.last_maintenance)}function V_(e){if(!uc(e)||!mc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==za.format||e.version!==1||typeof e.generated_at!="string"||!wt(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,n;for(let a of e.streams){if(!YA(a,t))throw new TypeError("Invalid history attestation stream");let o=a.id;if(n!==void 0&&o<=n)throw new TypeError("Invalid history attestation stream order");n=o}let{workspace_digest:i,...r}=e;if(Wa(A(r),t)!==i)throw new TypeError("History attestation rollup mismatch");return e}async function K_(e={}){let t=Re(e.hashAlgorithm),n=e.generatedAt??$();if(!wt(n))throw new TypeError("Invalid history attestation timestamp");let i=await lc(M(e.cwd??process.cwd(),e.pmRoot),t),r=i.filter(o=>o.stream===null);if(r.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${r.map(o=>o.id).join(", ")}`);let a={format:za.format,version:1,hash_algorithm:t,generated_at:n,streams:i.map(o=>o.stream)};return V_({...a,workspace_digest:Wa(A(a),t)})}async function Y_(e,t={}){let n=V_(e),i=await lc(M(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),r=new Map(i.map(l=>[l.id,l])),a=new Map(n.streams.map(l=>[l.id,l])),o=n.streams.filter(l=>!r.has(l.id)).map(l=>l.id),s=i.filter(l=>!a.has(l.id)).map(l=>l.id),c=i.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of n.streams){let u=r.get(l.id);u&&(u.digest!==l.stream_digest||A(u.stream)!==A(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:o.length+s.length+c.length+d.length===0,workspace_digest:n.workspace_digest,streams_checked:i.length,changed_streams:d.map(l=>l.id),missing_streams:o,added_streams:s,invalid_streams:c,transitions:d}}import X_ 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]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function tW(e,t){for(let i of["verify","output","hashAlgorithm"]){let r=e[i];if(!(i==="verify"&&typeof r=="object"&&r!==null)&&r!==void 0&&(typeof r!="string"||r.trim().length===0))throw new g(`history attest ${i} requires a nonempty string.`,y.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new g("history attest --verify cannot be combined with --output or --hash-algorithm",y.USAGE);let i;try{i=typeof e.verify=="string"?JSON.parse(await X_.readFile(e.verify,"utf8")):e.verify}catch{throw new g("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",y.USAGE)}return Y_(i,{pmRoot:t.path})}let n=await K_({pmRoot:t.path,hashAlgorithm:Re(e.hashAlgorithm)});if(e.output===void 0)return n;try{await X_.writeFile(e.output,`${JSON.stringify(n,null,2)}
|
|
59
|
-
`,{flag:"wx",mode:384})}catch{throw new g("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",y.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.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]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function
|
|
60
|
-
`)}var
|
|
61
|
-
`)}catch{}}function eC(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new g("Reindex mode must be one of keyword|semantic|hybrid",y.USAGE)}async function tC(e,t,n,i){let r=[];return{candidates:await rl(e,t,n,r,i),warnings:r}}async function _c(e,t,n,i,r){let a=Gt(F()),o=[];for(let s of t)if(!(r&&!r.has(s.metadata.id))){if(typeof s.body=="string"){o.push({metadata:s.metadata,body:s.body});continue}try{let c=await XA.readFile(s.item_path,"utf8"),d=vt(c,{format:s.item_format,schema:n,extensionFieldNames:a,onWarning:l=>i.push(l)});o.push({metadata:s.metadata,body:d.body})}catch{i.push(`item_list_item_read_failed:${$i.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function nC(e,t,n){let i=e.metadata;return{id:i.id,mode:t,updated_at:i.updated_at,corpus:sl(e,{fields:n})}}var Ln=Y;function iC(e){let t=F(),n=Ln(e.search?.provider);if(!n)return null;let i=Id(t,n);if(!i)return null;let r=i.runtime_definition??i.definition,a=Ln(r.name)??Ln(i.definition.name);if(!a)return null;let o=r.embedBatch,s=r.embed_batch,c=r.embed,d=typeof o=="function"?o:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:a,embedBatch:d,embed:l}}function rC(e){let t=F(),n=Ln(e.vector_store?.adapter);if(!n)return null;let i=Rd(t,n);if(!i)return null;let r=i.runtime_definition??i.definition,a=Ln(r.name)??Ln(i.definition.name);if(!a)return null;let o=r.upsert,s=r.delete;return{adapterName:a,...typeof o=="function"?{upsert:o}:{},...typeof s=="function"?{delete:s}:{}}}function hc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new g(`Invalid vector returned by ${t}`,y.GENERIC_FAILURE);return e}async function aC(e,t,n){let i=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let a=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:i}));if(!Array.isArray(a))throw new g(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,y.GENERIC_FAILURE);return a.map((o,s)=>hc(o,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new g(`Extension search provider "${e.name}" does not implement embed/embedBatch`,y.GENERIC_FAILURE);let r=[];for(let[a,o]of n.entries()){let s=await Promise.resolve(e.embed({input:o,settings:t,model:i}));r.push(hc(s,`extension search provider "${e.name}" embed output at index ${a}`))}return r}function tg(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function ng(e,t,n){let i=n?Mt(n.name,tg(e)):t?Mt(t.name,t.model):null;if(!i)throw new g("No embedding identity available for semantic reindex mode",y.USAGE);return i}function oC(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,i)=>n.localeCompare(i))}async function ig(e,t,n,i,r,a,o,s){let c=i?.name??n?.name,d=cl(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Ja(e),u=r.map(p=>dl(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(i)try{m=await aC(i,e,u),f=Mt(i.name,tg(e))}catch(p){if(!n)throw new g(`Extension search provider "${i.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,y.GENERIC_FAILURE);a.push(`Extension search provider "${i.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new g(`No embedding executor available for reindex mode '${t}'`,y.USAGE);let p=await ll(n,e,u,{onProgress:h=>{h.phase==="complete"&&(o.batches_completed=h.batch_index),oe(s,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});a.push(...p.warnings),o.batching=p.receipt,m=p.vectors,f=Mt(n.name,n.model)}if(oe(s,`embedding_complete vectors=${m.length}`),m.length!==r.length)throw new g(`Embedding output size mismatch (expected ${r.length}, received ${m.length})`,y.GENERIC_FAILURE);if(!f)throw new g(`No embedding identity available for reindex mode '${t}'`,y.USAGE);return{vectors:m,embeddingIdentity:f}}async function sC(e,t,n,i,r,a){let o=Object.keys(n);if(t){if(o.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:o.sort((s,c)=>s.localeCompare(c)),settings:i}))}catch(s){throw new g(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,y.GENERIC_FAILURE)}else o.length>0&&r.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${o.length}`);if(!e)return}e&&await pl(e,o,{},a)}async function rg(e,t,n,i,r){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:i}))}catch(a){throw new g(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${a instanceof Error?a.message:String(a)}`,y.GENERIC_FAILURE)}else r.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await ml(e,n)}}function cC(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function dC(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(i=>({id:i.metadata.id,type:i.metadata.type,status:i.metadata.status,priority:i.metadata.priority,updated_at:i.metadata.updated_at}))}}function lC(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=qn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new g(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,y.USAGE);let n=fr(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new g(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,y.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function uC(e){let t=H(e.settings,F()),n=await tC(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(i=>({metadata:i.metadata,body:typeof i.body=="string"?i.body:""}))}}async function mC(e){let t=await on(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return ng(e.settings,qn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&an(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(ZA))}async function pC(e){let t=await on(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=ng(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),i=new Set(e.metadataDocuments.map(d=>d.metadata.id)),r=oC(t.entries,i),a=an(t.embedding,n);e.forceFullSemantic&&!a&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let o=e.forceFullSemantic||a?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(o.map(d=>d.metadata.id)),c=s.size>0?await _c(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:r,resetRequired:a,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function fC(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await _c(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,oe(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let i=await ig(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...i,staleDocuments:n,vectorDimension:Va(i.vectors,"Reindex embeddings")}}async function hC(e){let t=await ig(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,i=t.embeddingIdentity,r=Va(n,"Reindex embeddings");if(!(!e.resetRequired&&(an(e.ledgerEmbedding,i)||hl(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:i,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let a=await fC(e);return n=a.vectors,i=a.embeddingIdentity,r=a.vectorDimension,{vectors:n,embeddingIdentity:i,staleDocuments:a.staleDocuments,vectorDimension:r,resetRequired:!0}}async function _C(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(oe(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new g(`Extension vector adapter "${t}" does not support upserting vectors.`,y.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,oe(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof g)throw t;if(!e.activeVectorStore)throw new g(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,y.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),oe(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){oe(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await ul(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,oe(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new g(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,y.USAGE)}function gC(e,t){return e.map((n,i)=>({id:n.metadata.id,vector:hc(t[i],`reindex embeddings output at index ${i}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function yC(e){oe(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await hC({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(oe(e.progressEnabled,"vector_reset_start"),await sC(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),oe(e.progressEnabled,"vector_reset_complete")):await rg(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=gC(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await _C({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:fl(t.embeddingIdentity,t.vectorDimension)}}async function wC(e){let t=await pC(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(a=>[a.metadata.id,a.metadata.updated_at]));if(oe(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return oe(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await rg(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let i=await yC({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let r=new Map(i.staleDocuments.map(a=>[a.metadata.id,a]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(a=>r.get(a.metadata.id)??a),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:i.embeddingMetadata}}async function vC(e){let t=$i.join(e.pmRoot,pc),n=$i.join(e.pmRoot,fc),i=Ja(e.settings),r=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(nC(o,e.mode,i))).join(`
|
|
48
|
+
`}function uS(e){return e.map((t,n)=>({...t,sequence:n+1}))}function aM(e,t,n){ps(e,"base");let i=ps(t,"ours"),r=ps(n,"theirs"),a=Math.min(i.length,r.length),o=0;for(;o<a&&i[o].eventId===r[o].eventId;)o+=1;if(o===i.length&&o===r.length)return{merged:Zr(i),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(o===r.length)return{merged:Zr(i),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:i.length-o,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(o===i.length)return{merged:Zr(r),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:r.length-o,entries_total:r.length,reanchored:!1};let s=i.slice(o),c=new Set(s.map(m=>m.eventId)),d=r.slice(o).filter(m=>!c.has(m.eventId)),l=[...s,...d].sort((m,f)=>{if(m.timestamp!==void 0&&f.timestamp!==void 0){let _=Lt(m.timestamp,f.timestamp);if(_!==0)return _}else{if(m.timestamp===void 0&&f.timestamp!==void 0)return 1;if(m.timestamp!==void 0)return-1}let p=c.has(m.eventId),h=c.has(f.eventId);return p!==h?Number(h)-Number(p):0}),u=uS([...i.slice(0,o),...l]);return{merged:Zr(u),strategy:"union_reanchor",common_entries:o,entries_from_ours:s.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var Rf=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],Af=["acceptance_criteria"],mS=["updated_at"];function Wt(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:A(e)===A(t)}function If(e,t,n){let i=l=>Array.isArray(l)?l:[],r=new Set(i(e).map(l=>A(l))),a=i(t),o=new Set(a.map(l=>A(l))),s=i(n),c=new Set(s.map(l=>A(l))),d=a.filter(l=>{let u=A(l);return!r.has(u)||c.has(u)});for(let l of s){let u=A(l);!o.has(u)&&!r.has(u)&&d.push(l)}return d}function bi(e){if(typeof e!="object"||e===null||Array.isArray(e))return A(e);let{provenance:t,...n}=e;return A(n)}function pS(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function fS(e,t,n){let i=l=>Array.isArray(l)?l:[],r=new Set(i(e).map(bi)),a=i(t),o=new Set(a.map(bi)),s=i(n),c=new Set(s.map(bi)),d=a.filter(l=>{let u=bi(l);return!r.has(u)||c.has(u)});for(let l of s){let u=bi(l);!o.has(u)&&!r.has(u)&&d.push(pS(l))}return d}function hS(e,t){return Lt(String(e),String(t))>=0?e:t}function Cf(e,t,n,i){return Wt(t,n)?{value:t,from_theirs:!1,conflict:!1}:Wt(e,t)?{value:n,from_theirs:!0,conflict:!1}:Wt(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:i==="theirs"?n:t,from_theirs:i==="theirs",conflict:!0}}function Tf(e,t,n,i,r,a,o){let s=Cf(e,t,n,i);if(!s.conflict)return{...s,conflict:!1};if(r==="preferred_side")return{...s,resolution_basis:"requested_preference",retained_side:s.from_theirs?"theirs":"ours"};let c=Lt(a,o);if(r==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=A(V(n)).localeCompare(A(V(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function fs(e){return{...e.metadata}}function hs(e,t,n){try{let i=Ud(bt(e,{...n,requireSupportedFormat:!0}),n),r=Object.entries(i.metadata).find(([,a])=>Rn(a))?.[0];if(r!==void 0)throw new TypeError(`metadata field ${r} uses the reserved missing-scalar evidence marker`);return i}catch(i){throw i instanceof g&&i.context?.code==="item_format_version_unsupported"?i:new g(`Item merge input (${t}) is not a readable item document: ${String(i)}`,y.GENERIC_FAILURE)}}function _S(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?fS(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?If(Xi(e.baseValue),Xi(e.oursValue),Xi(e.theirsValue)).join("; "):If(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,Wt(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function gS(e){let t=Tf(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:V(e.baseValue),ours:V(e.oursValue),theirs:V(e.theirsValue),retained:V(t.value),discarded:V(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function $f(e,t,n,i,r,a,o){let s=new Set([...Rf,...Af]),c=new Set(mS),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let m=e[u],f=t[u],p=n[u];if(!_S({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:s,accumulator:l})){if(c.has(u)){l.merged[u]=hS(f,p);continue}gS({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:i,conflictResolution:r,oursUpdatedAt:a,theirsUpdatedAt:o,accumulator:l})}}return l}function oM(e,t,n,i={}){let r=i.preferred??"ours",a=i.conflictResolution??"preferred_side",o=hs(t,"ours",i),s=hs(n,"theirs",i);if(e.trim().length===0)throw new g("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",y.CONFLICT,{code:"item_identity_conflict",item_id:o.metadata.id});let c=hs(e,"base",i);if(c.metadata.id!==o.metadata.id||c.metadata.id!==s.metadata.id)throw new g("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",y.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let d=fs(c),l=fs(o),u=fs(s),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:h,conflictDecisions:_}=$f(d,l,u,r,a,o.metadata.updated_at,s.metadata.updated_at),w=Tf(c.body,o.body,s.body,r,a,o.metadata.updated_at,s.metadata.updated_at);w.conflict?(f.push("body"),_.push({field:"body",base:V(c.body),ours:V(o.body),theirs:V(s.body),retained:V(w.value),discarded:V(w.from_theirs?o.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body");let v=m;return v.pm_format_version=Md(Math.max(...[c.metadata,o.metadata,s.metadata,v].map(Nd))),{merged:Fd({metadata:v,body:w.value},i),conflict_fields:f,fields_from_theirs:p,union_fields:h,conflict_decisions:_,requested_preference:r,requested_preference_applied:a==="preferred_side",conflict_resolution:a}}function _s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gs(e,t){let n=$e(e);if(n)throw new g(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,y.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new g(`JSON merge input (${t}) is not valid JSON.`,y.GENERIC_FAILURE)}}function yS(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let i=d=>{let l=new Map;for(let u of d){let m=A(u);l.set(m,(l.get(m)??0)+1)}return l},r=i(e),a=i(t),o=i(n);for(let[d,l]of r)if((a.get(d)??0)<l||(o.get(d)??0)<l)return null;let s=new Map(a),c=[];for(let d of n){let l=A(d),u=s.get(l)??0;u>0?s.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function wS(e,t,n,i,r,a,o){if(!_s(t)||!_s(n))return null;let s=_s(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=r.length>0?`${r}.${l}`:l,m=vS(s,t,n,l,i,u,a,o);m!==void 0&&(c[l]=m)}return c}function Df(e,t,n,i,r,a,o){if(Wt(t,n))return t;let s=yS(e,t,n);if(s!==null)return s.acceptedTheirs&&o.push(r),s.merged;let c=wS(e,t,n,i,r,a,o);if(c!==null)return c;let d=Cf(e,t,n,i);return d.conflict?a.push(r):d.from_theirs&&o.push(r),d.value}function vS(e,t,n,i,r,a,o,s){let c=Object.prototype.hasOwnProperty.call(t,i),d=Object.prototype.hasOwnProperty.call(n,i),l=Object.prototype.hasOwnProperty.call(e,i);if(c&&d)return Df(e[i],t[i],n[i],r,a,o,s);if(c){if(l&&Wt(e[i],t[i])){s.push(a);return}return l?(o.push(a),r==="theirs"?void 0:t[i]):t[i]}if(!(l&&Wt(e[i],n[i])))return l?(o.push(a),r==="theirs"?n[i]:void 0):(s.push(a),n[i])}function sM(e,t,n,i={}){let r=i.preferred??"ours",a=gs(e,"base"),o=gs(t,"ours"),s=gs(n,"theirs"),c=[],d=[],l=Df(a,o,s,r,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
|
|
49
|
+
`,conflict_paths:c,paths_from_theirs:d,preferred:r}}import ea from"node:path";import{execFile as bS}from"node:child_process";import{createHash as Of}from"node:crypto";import{readdir as kS}from"node:fs/promises";import ES from"node:path";import{promisify as SS}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]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var mt=SS(bS),Qr=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function hM(e,t,n){let i=t.trim(),r=/^(['"])(.*)\1$/su.exec(i)?.[2]??i;for(let a of["rebase-merge","rebase-apply"])try{let{stdout:o}=await mt("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Vn(o.trim(),128))?.trim();if(s===void 0||!Qr.test(s))continue;let{stdout:c}=await mt("git",["rev-parse","--verify",`${s}:${r}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:s,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(a=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(a)))try{let{stdout:a}=await mt("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!Qr.test(o))return;let{stdout:c}=await mt("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Of(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:o,original_blob:d}}catch{}}function Pf(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&Qr.test(t.original_head)&&typeof t.original_blob=="string"&&Qr.test(t.original_blob)}async function Lf(e,t,n,i){if(i!==void 0&&Of(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(i)}\0`).update(i).digest("hex")!==n.original_blob)return!1;try{let{stdout:r}=await mt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),a=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await kS(r.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await mt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await mt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await mt("git",["hash-object","--",ES.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await mt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!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]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var xS=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,IS=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,na=2048,RS=64,AS=1e5,CS=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function pt(e){return xS.test(e)}var TS=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ia="bounded_non_sensitive_scalars_v1",$S=new Set(["open","in_progress","blocked","closed","canceled"]),DS=new Set(["risk","confidence","severity"]),OS=new Set(["low","medium","high","critical"]),Mf=new Map([["priority",new Set([0,1,2,3,4].map(A))],["status",new Set([...$S].map(A))],...[...DS].map(e=>[e,new Set([...OS].map(A))])]);function tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jf(e,t){return Object.keys(e).every(n=>t.has(n))}function ta(e){return Array.isArray(e)&&e.length<=na&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function ki(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let i=t.pop();if(n+=1,n>AS||i.depth>RS)return!1;if(Array.isArray(i.value))for(let r of i.value)t.push({value:r,depth:i.depth+1});else if(tt(i.value))for(let r of Object.values(i.value))t.push({value:r,depth:i.depth+1})}return!0}function Ff(e){if(!tt(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[jf(e,TS),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),ki(e.base),ki(e.ours),ki(e.theirs),ki(e.retained),ki(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function PS(e){if(!tt(e))return!1;let t=Object.entries(e);return t.length<=na&&t.every(([n,i])=>n.length>0&&n.length<=256&&typeof i=="string"&&/^[a-f0-9]{64}$/u.test(i))}function LS(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||ea.posix.isAbsolute(e))return!1;let n=ea.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&ea.posix.basename(n,ea.posix.extname(n))===t}function NS(e){return!ta(e.fields_from_theirs)||!ta(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>na||!e.decisions.every(Ff)?!1:e.merged_field_hashes===void 0||PS(e.merged_field_hashes)}function MS(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],i=[void 0,"clone_local","hash_only","bounded_inline","mixed"],r=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&i.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ia)&&r.includes(e.evidence_source)}function jS(e){return typeof e.created_at=="string"&&Qt(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Qt(e.reconciled_at))}function Nf(e,t){if(!tt(t)||oa(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(r=>r==="pm_value_hash"||r==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let i=t.pm_value;return(i===null||Mf.get(e)?.has(A(i))===!0)&&At(i)===t.pm_value_hash}function FS(e){if(!e.decisions.every(i=>i.base===null&&i.ours===null&&i.theirs===null&&Nf(i.field,i.retained)&&Nf(i.field,i.discarded)))return!1;let t=e.decisions.reduce((i,r)=>i+(tt(r.retained)&&Object.hasOwn(r.retained,"pm_value")?1:0)+(tt(r.discarded)&&Object.hasOwn(r.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===ia)}function US(e){return e.operation!==void 0&&!Pf(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function HS(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!jf(e,CS)?"required_fields":typeof e.id!="string"||!pt(e.id)?"receipt_id":typeof e.item_id!="string"||!IS.test(e.item_id)?"item_id":LS(e.item_path,e.item_id)?null:"item_path"}function ra(e,t){if(!tt(e))return"required_fields";let n=HS(e);return n!==null?n:US(e)?NS(e)?MS(e)?jS(e)?t==="durable"&&!FS(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function aa(e){if(!tt(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(i=>!tt(i)||!Object.hasOwn(i,"retained")||!Object.hasOwn(i,"discarded")?i:{base:V(void 0),ours:V(void 0),theirs:V(void 0),...i})}}function Uf(e){if(!tt(e))return;if(!ta(e.fields_from_theirs))return"fields_from_theirs";if(!ta(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>na)return"decisions";let t=e.decisions.findIndex(n=>!Ff(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function ws(e,t){return ra(e,t)===null}function oa(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function vs(e,t){let n=Rn(t),i=At(n?void 0:t);return!n&&(t===null||Mf.get(e)?.has(A(t))===!0)?{pm_value_hash:i,pm_value:t}:{pm_value_hash: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]="7bab0a8e-842c-5588-a0b2-22ef261ddb06")}catch{}})();var JS=BS(zS),sa=100;async function bs(e){try{let{stdout:t}=await JS("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Wf(e,t){let n=ae.dirname(ae.resolve(e,t));for(let i=0;i<12;i+=1){if(await D(ae.join(n,"settings.json")))return n;let r=ae.dirname(n);if(r===n)break;n=r}return null}function An(e){return ae.join(e,"merge-receipts")}function Tt(e){return`${e}.json`}async function Hf(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Vn(e.receiptPath,_r)}catch(a){if(yt(a))return null;throw a}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=aa(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!ws(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ae.basename(e.receiptPath)!==Tt(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:i,...r}=n;return{path:e.receiptPath,fingerprints:Si(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...r,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
50
|
+
`}}function Ei(e,t=!1){return xe(A({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:xe(A(V(n.retained))),discarded_hash:xe(A(V(n.discarded)))})):ca(e).decisions}))}function Si(e){let t=[Ei(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Ei(e,!0)),t}function VS(e,t){let{reconciled_at:n,settlement:i,...r}=e;return t.state==="reconciled"?{...r,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...r,state:"pending"}}async function KS(e,t,n){let i=new Map;for(let r of t){let a=e.get(r.id);if(r.state!=="reconciled"||a===void 0)continue;let o=i.get(a.item_id);if(o===void 0){try{o=await Me(ae.join(n,"history",`${a.item_id}.jsonl`),a.item_id),kt(o).ok||(o=[])}catch{o=[]}i.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=A({...ca(a),...s?{reason:a.settlement,operation:a.operation}:{}});if(!o.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[s?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(m=>A(m)===c)})){let{reconciled_at:d,settlement:l,...u}=a;e.set(a.id,{...u,state:"pending"})}}}function ca(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:oa(t.retained)??At(Rn(t.retained)?void 0:t.retained),discarded_hash:oa(t.discarded)??At(Rn(t.discarded)?void 0:t.discarded)}))}}async function FM(e){let t=await bs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,r=ae.basename(i,ae.extname(i)),a={version:1,id:WS(),item_path:i.replaceAll("\\","/"),item_id:r,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(s=>({...s,base:V(s.base),ours:V(s.ours),theirs:V(s.theirs),retained:V(s.retained),discarded:V(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:$(),value_availability:"clone_local"};await Fn(t),await Z(ae.join(t,Tt(a.id)),`${JSON.stringify(a,null,2)}
|
|
51
|
+
`);let o=await Wf(e.cwd,a.item_path);if(o!==null){let s=An(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:vs(u.field,u.retained),discarded:vs(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),l={...a,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:ia};await Fn(s),await Z(ae.join(s,Tt(a.id)),`${JSON.stringify(l,null,2)}
|
|
52
|
+
`)}return a}async function zf(e,t){let n;try{n=await qS(e)}catch(s){let c=await YS(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let i=[],r=0,a=[],o=(s,c)=>{if(r+=1,a.length>=sa)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...pt(d)?{receipt_id:d}:{candidate_name_hash:xe(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await XS(e,s,t);c.receipt!==void 0?i.push(c.receipt):o(s,c)}return{receipts:i,invalid_evidence_count:r,invalid_evidence:a,invalid_evidence_truncated:r>a.length}}async function YS(e,t,n=GS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ae.dirname(i);if(a===i)return!0;i=a}}async function XS(e,t,n){let i;try{i=await Vn(ae.join(e,t),_r)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=aa(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=ra(r,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:Uf(r)}:{}};let o=r;if(t!==Tt(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function ZS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-KHWT44EK.js"),r=await QS(t),a=await i(r?.workspace??e,An(t),n.map(o=>Tt(o.id)),_r,r?.directory);return n.flatMap(o=>{try{let s=aa(JSON.parse(a.get(Tt(o.id))??""));if(ra(s,"durable")!==null)return[];let c=s,d=Si(o);return c.id===o.id&&Si(c).some(l=>d.includes(l))?[o.id]:[]}catch{return[]}})}async function QS(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,i=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!i))try{if(await Ct(e)!==await Ct(i))return;let r=ae.relative(await Ct(t),await Ct(n)),a=r===".."||r.startsWith(`..${ae.sep}`)||ae.isAbsolute(r),o=An(a?ae.join(await Ct(t),".agents","pm"):await Ct(n)),[s,c]=await Promise.all([Ct(o),Ct(An(n))]);return s!==c?void 0:{workspace:t,directory:o}}catch{return}}async function ft(e,t={}){let n=await bs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await zf(n,"clone_local"),r=t.pmRoot??ae.join(e,".agents","pm"),a=await zf(An(r),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of i.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?Si(u):[Ei(u)]).includes(Ei(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<sa&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}o.set(u.id,m===void 0?u:VS(u,m))}await KS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await ZS(e,r,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...o.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:i.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...i.invalid_evidence,...a.invalid_evidence,...c].slice(0,sa),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>sa,clone_local_evidence_resolved:n!==null}}function qf(e,t,n){let i=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),r=[...e].filter(a=>!i.has(a));if(r.length!==0)throw new g(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,y.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Cn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function UM(e,t,n={}){let i=await bs(e);if(i===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let r=t.evidence_source??"clone_local";if(!ws(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=ae.join(i,Tt(t.id)),s=await Wf(e,t.item_path),c=s===null?null:ae.join(An(s),Tt(t.id)),d=(await Promise.all([Hf({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Hf({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[Ei(t)]:Si(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function HM(e){let t=await ft(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as e0}from"node:crypto";import da 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 t0="2026-08-09T16:15:18.000Z",Bf=Symbol("pre-durable-disposition-eligible");function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ks(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let i=e[n];if(!(n in e)||typeof i!="string"||i.length===0||i.length>256||i.includes("\0")||t.has(i))return!1;t.add(i)}return!0}function Gf(e){return ht(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 Jf(e,t){if(typeof e!="string")return!1;let n=da.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!da.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(da.posix.basename(n)===`${t}.toon`||da.posix.basename(n)===`${t}.md`)}function n0(e,t){return typeof e.receipt_id=="string"&&pt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Jf(e.item_path,t)}function Vf(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,a=Array.isArray(r)?new Set(r.flatMap(o=>Gf(o)?[o.field]:[])):new Set;return ks(t)&&ks(n)&&ks(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Gf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function i0(e,t){return n0(e,t)&&Vf(e)}function r0(e,t){return typeof e.receipt_id=="string"&&pt(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&&Jf(e.item_path,t)&&Vf(e)}function a0(e){return e[Bf]===!0}function Kf(e,t){if(!ht(e)||!ht(e.context))return[];let n=e.context.merge;return!ht(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!ht(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:i0(i,t),[Bf]:r0(i,t),...typeof e.ts=="string"&&Qt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Yf(e,t,n){if(!ht(e)||e.op!=="merge_reconcile")return[];if(!ht(e.context)||!ht(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!ht(r)||typeof r.receipt_id!="string"||!pt(r.receipt_id)||typeof r.original_history_line!="number"||!Number.isSafeInteger(r.original_history_line)||r.original_history_line<1||typeof r.original_event_ts!="string"||!Qt(r.original_event_ts)||r.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:r.receipt_id,originalHistoryLine:r.original_history_line,originalEventTimestamp:r.original_event_ts,auditHistoryLine:n,reason:r.reason}])}function Xf(e,t,n=[]){let i=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;i.set(o,Math.max(i.get(o)??0,a.auditHistoryLine))}let r=a=>a0(a)&&a.eventTimestamp!==void 0&&Lt(a.eventTimestamp,t0)<0&&(i.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!r(a)).map(a=>({item_id:a.itemId,history_line:a.line,...pt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:e0("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as o0}from"node:buffer";import{readFile as s0}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]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function c0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new g("History salvage cannot discard a potentially complete record with trailing corruption.",y.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("History salvage would conceal interior corruption or a malformed record.",y.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new g("History salvage requires complete history records before the invalid tail.",y.CONFLICT,{code:"history_salvage_refused"});return n}function d0(e){if($e(e))throw new g("Resolve history merge conflicts before salvage.",y.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,i,r=0;for(let[o,s]of e.split(`
|
|
53
|
+
`).entries()){if(!s.trim()){n+=s.length+1;continue}let c=c0(s);if(c===null){i===void 0&&(i=n,r=o+1),n+=s.length+1;continue}if(i!==void 0)throw new g("History salvage would discard a record or conceal interior corruption.",y.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=s.length+1}let a=kt(t);if(!a.ok||a.item_hash_version===void 0)throw new g("History salvage requires a nonempty verified prefix.",y.CONFLICT,{code:"history_salvage_refused",verification_errors:a.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:a.item_hash_version,prefix:i===void 0?e:e.slice(0,i),receipt:i===void 0?null:{first_invalid_line:r,discarded_bytes:Buffer.byteLength(e.slice(i)),discarded_sha256:xe(e.slice(i)),retained_entries:t.length}}}async function l0(e,t,n){if(!e.located)return{itemRaw:null,document:n};let i=await ul(e.located,{schema:t.schema});return{itemRaw:i.raw,document:i.document??n}}async function Zf(e){let t;try{t=await s0(e)}catch(n){if(j(n))return null;throw n}if(!o0(t))throw new g("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",y.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function Qf(e){let{subject:t,settings:n,options:i,author:r}=e;if([i.normalizeProvenance,i.auditOperation,i.auditContext,i.auditContextById,i.forceAuditEntry,i.mergeReceiptProof,i.mergeReceiptProofById].some(Boolean))throw new g("Tail salvage cannot be combined with other repair modes.",y.USAGE);let a=await Zf(t.historyPath);if(a===null)throw new g(`No history stream exists for ${t.id}.`,y.NOT_FOUND);await Ne({path:t.historyPath,scope:"project"});let o=d0(a),s=il(o.entries,o.entries.length-1),c=Vd(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new g("History belongs to another item; salvage refused.",y.CONFLICT,{code:"history_salvage_refused"});let d=await l0(t,n,c),l=Eo({itemDocument:d.document,subjectId:t.id,author:r,force:i.force,settings:n}),u=o.itemHashVersion,m=i.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await re(e.pmRoot,t.id,n.locks.ttl_seconds,r,!!i.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Zf(t.historyPath),_=await ge(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=_?await B(_.itemPath):null;if(h!==a||w!==d.itemRaw)throw new g("History or item changed while waiting for salvage lock; retry.",y.CONFLICT);let v=rr({...Jd({hashAlgorithm:Re(o.entries.at(-1).hash_algorithm),nowIso:$(),author:r,op:"history_salvage",before:c,after:c,message:i.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await Cr({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
|
|
54
|
+
`}),l.push(...await K({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:$()}}import{realpath as rh}from"node:fs/promises";import Es from"node:path";import ah from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6d2870f-ebba-580a-85e9-3eb44e533d08")}catch{}})();function eh(e,t){return t==="body"?e.body:e.metadata[t]}function u0(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function m0(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function th(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(i=>u0(e,i)))return t;let n=t.map(i=>e==="comments"?i:m0(i));return[...new Map(n.map(i=>[A(i),i])).values()]}function Ss(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let i=new Set;return e.every(r=>{let a=t.findIndex((o,s)=>!i.has(s)&&Ss(r,o));return a<0?!1:(i.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([i,r])=>Object.hasOwn(n,i)&&Ss(r,n[i]))}function nh(e,t){let n=new Set(t),i=[];for(let r=e.length-1;r>=0&&n.size>0;r-=1){let a=e[r],o=new Set;for(let c of sr(a.patch))o.add(dr(c.path)),c.from&&o.add(dr(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);i.push({index:r+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return i.reverse()}function p0(e,t,n){let i=ah.compare(t,n);if(i.length===0)return;let r=new Set;for(let p of i)r.add(dr(p.path));let a=new Set([...r].filter(p=>Ss(th(p,eh(t,p)),th(p,eh(n,p))))),o=new Set([...r].filter(p=>!a.has(p))),s=nh(e,o),c=nh(e,a),d=[...r].sort((p,h)=>p.localeCompare(h)),l=[...o].sort((p,h)=>p.localeCompare(h)),u=[...a].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:r.size,reconciled_fields:d,reverted_field_count:o.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function f0(e){try{return await rh(e)}catch{return null}}async function h0(e){if(await f0(Es.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let i=Object.keys(n).sort();if(t.length!==i.length||t.some((a,o)=>a!==i[o]))return null;let r=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:r[a];return[At(o),xe(A(V(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function _0(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await rh(e.itemPath),i=[];for(let o of t){let s=await h0({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&i.push(s)}let r=new Set(i.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return i.length>0&&(a===void 0||a.length>0&&a.every(o=>r.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:i.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function ih(e,t,n,i){if(e===void 0)return;let{receipt:r,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:Es.relative(a,t.currentItemPath).split(Es.sep).join("/");if(!n||i.entriesRehashed!==0||i.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==r.item_path||r.operation===void 0||!await Lf(a,r.item_path,r.operation,t.currentItemRawBeforeLock))throw new g("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function g0(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),n=e.options.mergeReceiptProof?await ft(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,i=n?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[];qf(t,n,e.options.dryRun===!0);let r=e.options.mergeReceiptProof?await _0({proof:{...e.options.mergeReceiptProof,receipts:i},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new g(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let a=r?.trusted?i.filter(o=>r.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:a.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:a.map(ca)}}:e.options.auditContext}}function y0(e,t,n){let i=e.located?.itemPath??null,r=t.loadedItem,a=t.entries;if(!r)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=or(r.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:tn(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:r.raw,loadedItem:r}}function w0(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function v0(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,i=Re(e.reanchorEntries.at(-1)?.hash_algorithm),r=tn(e.finalReplay,e.itemHashVersion,i),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(a),s=tn(n,e.itemHashVersion,i),c={hash_algorithm:i,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?ah.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(rr({...c,event_class:zd(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function b0(e,t,n){let i=[];return e||i.push("history_repair_no_changes"),t>0&&i.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&i.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),i}async function xs(e,t,n){let{pmRoot:i,settings:r,typeRegistry:a}=await Qa(n.path),o=await Ol(i,e,r,a.type_to_folder);return t.salvageTail===!0?Qf({pmRoot:i,subject:o,settings:r,typeRegistry:a,options:t,author:z(t.author,r.author_default)}):Gu({pmRoot:i,subject:o,settings:r,typeRegistry:a,operation:"history-repair",options:t,transform:s=>E0({pmRoot:i,subject:o,options:t},s)})}function k0(e,t,n){let i=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(r=>r.record_hash_version!==void 0&&r.op==="merge_reconcile"&&A(r.context)===A(n));return e.forceAuditEntry===!0&&!i}async function E0(e,t){let{pmRoot:n,subject:i,options:r}=e,a=t.entries,o=t.verification,s=kt(a),c=r.normalizeProvenance?Fu(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=Kd(c.entries),l=new Set(c.entries.map(P=>P.item_hash_version).filter(P=>P!==void 0)),u=cr(c.entries,d),m=y0(i,t,d);await ih(r.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=tn(f,d),h=!1;if(m.currentItemReplay!==null){let P=tn(m.currentItemReplay,d);h=!p.some((x,q)=>x===P[q])}let _=h&&m.currentItemReplay?p0(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await g0({options:r,pmRoot:n,subjectId:i.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,k0(r,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,I=!!r.dryRun,C=w0({message:r.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=v0({reanchorEntries:u.entries,changed:E,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:C,auditOperation:r.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),O=b0(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>ih(r.mergeAbandonmentProof,m,o.ok,u),report:({verification:P,warnings:x})=>({id:i.id,dry_run:I,changed:E,history:{path:i.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:P.ok,verify_errors:P.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:r.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...O,...x])].sort((q,Se)=>q.localeCompare(Se)),generated_at:$()})}}function P1(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function L1(e,t){if(e.salvageTail===!0)throw new g("Tail salvage requires one explicit item ID; --all is not supported.",y.USAGE);let{pmRoot:n,settings:i,typeRegistry:r}=await Qa(t.path),a=[],o=await at(n,i.item_format,r.type_to_folder,a,i.schema,{forceSourceScan:!0}),s=await Ht(n,o),c=e.normalizeProvenance?await Uu(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await xs(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(_=>`${f}:${_}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await Wd(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_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]="11486e17-e6da-5770-8621-f59a17bb4922")}catch{}})();var S0=new Set(Sl),oh=25,x0=be.join("runtime","telemetry","events.jsonl"),I0=be.join("runtime","telemetry","state.json"),R0=2500,A0=500,sh=Al-3,C0=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function $s(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 Ds(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Tn(e){return e.trim().toLowerCase()}function As(e,t){let n=Tn(e),i=Tn(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Os(e){try{return(await _t.stat(e)).isDirectory()}catch{return!1}}async function T0(e){let t=(await _t.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>_t.readdir(be.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>Un.some(a=>r.name.endsWith(a))).map(r=>be.parse(r.name).name)))}async function $0(e,t,n,i){let r=await Ne({path:e,scope:"project"}),a=t!=="_workspace"&&!i.has(t);if(!n.enabled&&!a)return{warnings:r,overThreshold:!1,classification:"live"};let o;try{o=await _t.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function D0(e,t,n){let i=be.join(e,"history");if(!await Os(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await _t.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),a=t.enabled?t.max_entries:null,o=[],s=[],c=[],d=[];for(let l of r){let u=be.join(i,l),m=l.slice(0,-6),f=await $0(u,m,t,n);o.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&d.push(m),f.overThreshold&&s.push(m)}return{count:r.length,warnings:[...o,...s.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:s,max_entries:a,tombstones:c,orphaned:d}}function Cs(e,t){return be.relative(e,t).replaceAll("\\","/")}async function ch(e,t){let n=[...new Set(Object.values(t))].sort((r,a)=>r.localeCompare(a)),i=[];for(let r of n){let a=be.join(e,r),o=[];try{o=await _t.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&j(s))continue;continue}for(let s of o)Un.some(c=>s.toLowerCase().endsWith(c))&&i.push(be.join(a,s))}return i.sort((r,a)=>Cs(e,r).localeCompare(Cs(e,a))),i}function O0(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function P0(e,t,n){let i=await ch(e,t),r=[],a=[],o=[],s=[],c=Gt(F());for(let d of i){let l=Cs(e,d),u;try{u=await _t.readFile(d,"utf8")}catch{r.push(l);continue}let m=$e(u);if(m){a.push({path:l,...m});continue}try{let f=bt(u,{format:Mc(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:er(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function L0(e){let t=be.join(e,"history"),n=[],i=[],r=[],a=[],o=[],s=[];try{s=(await _t.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){O0(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await _t.readFile(be.join(t,c),"utf8")}catch{n.push(d);continue}let u=$e(l);if(u){i.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...Kf(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Yf(p,d,f+1))}catch{r.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:i,invalidJson:r,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function dh(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 N0(e,t,n,i,r,a){let o=await P0(e,t,n),s=await L0(e),c=tr(o.formatVersions,Wn,Qi),d=fe(n),l=hr(a,x=>jd(x,d),Jn()),u=await Xr(e),m=await St(e),f=await vf(e,m),p=await bf(e,m,i,r),h=m===null?null:await un(m),_=await ft(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(_.durable_receipt_ids),v=Xf(s.mergeReceiptReferences,w,s.mergeReceiptDispositions),E=v.missing,k=_.receipts.filter(x=>x.state==="pending"),{pendingDecisions:I,lossless:C}=Cn(k),S=h?.status==="missing"&&h.missing_keys.length===5&&h.drifted_keys.length===0,b=[...o.unreadable.map(x=>`integrity_item_unreadable:${x}`),...o.conflictMarkers.map(x=>`integrity_item_conflict_marker:${x.path}:L${x.line}`),...o.parseFailures.map(x=>`integrity_item_parse_failed:${x}`),...s.unreadable.map(x=>`integrity_history_unreadable:${x}`),...s.conflictMarkers.map(x=>`integrity_history_conflict_marker:${x.id}:L${x.line}`),...s.invalidJson.map(x=>`integrity_history_invalid_json:${x.id}:L${x.line}`),...c.outdated.map(x=>`integrity_item_outdated_format_version:${x}`),...c.ahead.map(x=>`integrity_item_ahead_format_version:${x}`),...dh(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...h!==null&&h.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${h.missing_keys.length+h.drifted_keys.length}`]:[],...p.warnings,...f.warnings,...I.length>0?[`merge_decisions_unreviewed:${I.length}`]:[],...C.length>0?[`merge_receipts_pending:${C.length}`]:[],...kf({invalidEvidenceCount:_.invalid_evidence_count,missingHistoryReferenceCount:E.length})],O=[...new Set(b)].sort((x,q)=>x.localeCompare(q)),P=O.filter(x=>!x.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:P.length===0?"ok":"warn",ok:P.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.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:h===null||h.status==="ok"?0:h.missing_keys.length+h.drifted_keys.length,merge_fence:p.count,ignored_merge_artifacts:f.rules.length,pending_merge_decisions:I.length,lossless_merge_receipts:C.length,invalid_merge_receipt_evidence:_.invalid_evidence_count,missing_merge_receipt_history_references:E.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.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:Fe(l.relations,Ju)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.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:h===null?null:{...h,required:r},merge_fence:p.audit,ignored_merge_artifacts:f.rules,pending_merge_decision_items:[...new Set(I.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),lossless_merge_receipt_items:[...new Set(C.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),invalid_merge_receipt_evidence_details:_.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:_.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:E.slice(0,So),missing_merge_receipt_history_reference_details_truncated:E.length>So}},warnings:O,gitWorkspaceRoot:m,pendingMergeReceipts:k}}function M0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function j0(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:M0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function F0(e,t){return Y(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function U0(e){let t=Y(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function H0(e){return Y(e.reason)??Y(e.error)??Y(e.message)}function Is(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let i=(e.name??"").localeCompare(t.name??"");return i!==0?i:(e.id??"").localeCompare(t.id??"")}function z0(e){let t=[],n=[],i=[];e.forEach((a,o)=>{let s=F0(a.definition,o),c=U0(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){i.push({layer:a.layer,name:a.name,id:s,status:c,reason:H0(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Is),n.sort(Is),i.sort(Is);let r=[...i.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:i,applied_count:t.length,pending_count:n.length,failed_count:i.length},warnings:r}}function lh(e,t,n,i,r,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>Ds(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=d.map(oi).filter(_=>_!==void 0),h=Qo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(i.failed_count>0||i.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Mi.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.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&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.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:i.failed_count,migration_pending_count:i.pending_count,managed_state_warning_count:r,managed_extension_entries_count:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function W0(e,t,n){let i=await os(Be(e)),r=await Je({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(S=>j0(S)),o=await Mu(r.loaded,Be(e)),s=await Ve({...r,loaded:r.loaded}),[c,d]=await Promise.all([he(r.roots.project),he(r.roots.global)]);await as(e,s.registrations.migrations);let l=z0(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.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}}},m=new Set(c.state.entries.map(S=>Tn(S.name))),f=new Set(d.state.entries.map(S=>Tn(S.name))),p=[...new Map(r.loaded.filter(S=>!(S.layer==="project"?m:f).has(Tn(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let O=`${S.layer}:${S.name}`,P=`${b.layer}:${b.name}`;return O.localeCompare(P)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),_=p.filter(S=>As(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!As(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],E=[...i.warnings,...r.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=gi(E),I=yi(),C=lh(E,r.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,_,w);return{check:{name:"extensions",status:E.length===0?"ok":"warn",ok:E.length===0,details:{...r,loaded:a,warnings:E,activation:u,author_manifest:i,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:I,capability_guidance:k,host_version_census:o}},warnings:E}}function Ts(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Vu(e,oh);return{values:n.values,truncated:n.truncated,total:e.length}}function la(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function q0(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return S0.has(e)?e:null}function ua(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 uh(e){let t=0,n=0,i=0,r=0,a=0;for(let o of e.split(`
|
|
55
|
+
`)){let s=o.trim();if(s.length!==0){i+=1;try{let c=JSON.parse(s);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,a=Math.max(a,d),d>=sh&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:a}}function G0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function B0(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 J0(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Xa().telemetry_disabled?void 0:{attempted:!0,...await mh(n)}}function V0(e,t,n){let i=[];if(t.invalidRows>0&&i.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return i;let r=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!r||a>r),s=!r,c=t.validEntries>=A0;return(o||s||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function K0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Y0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Rl?[`telemetry_schema_version_behind:${t}`]:[]}function X0(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,i=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&r&&(!i||r>=i)?[`telemetry_otel_export_failing:${n}`]:[]}function Z0(){return{...Xa(),pm_no_telemetry:la("PM_NO_TELEMETRY"),telemetry_otel_disabled:la("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:la("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:q0()}}function Q0(e,t){return e.telemetry.enabled&&t.validEntries>0}function ex(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function mh(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(R0)});return{probe_url:ua(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of C0){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:ua(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function tx(e,t){let n=Ui(process.cwd()),i=be.join(n,x0),r=be.join(n,I0),a=await B(i),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?uh(a):G0(),d=await B(r),{runtimeState:l,stateParseFailed:u}=B0(d),m=e.telemetry.endpoint.trim(),f=ua(m),p=await J0(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...V0(e,c,l),...K0(p),...Y0(p),...X0(e,l));let _=Q0(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:i,queue_exists:o,queue_entries:c.validEntries,queue_draining:ex(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:sh,queue_max_attempts:c.maxAttempts,runtime_state_path:r,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:p??{attempted:!1},env_overrides:Z0()}},warnings:h}}async function nx(e){let t;try{t=await _m(e)}catch(i){let r=i instanceof Error?i.message:String(i);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:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}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 ix(e){let t="metadata",n=e.items,i=await Ht(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(r.length>0){n=await at(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Ht(e.pmRoot,n),a=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,E)=>v.localeCompare(E));let w=new Set(a);o=r.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=i,_=[...s.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}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:r.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function rx(e,t){let n=ur(e),i=Bn(n.settings),r=fr(n.settings,t),a=i.active?Mt(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(i.active&&r.active)}}function ax(){return{refreshed:[],skipped:[],warnings:[]}}async function ox(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?ax():El(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function sx(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&sn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function cx(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,i)=>n.localeCompare(i))}function dx(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function ph(e,t){let n=t.providerResolution.active?.name??null,i=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Va(n,e.search?.provider??null),vector_store_active:i,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Va(i,e.vector_store?.adapter??null)}}function lx(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function ux(e,t,n){return e.enabled&&n.length>0&&t}async function mx(e,t,n,i,r){let a=rx(t,e),o=await cn(e),s=a.semanticRuntimeAvailable?eo(n,o.entries):[],c=await ox({pmRoot:e,snapshot:a,refreshPolicy:i,staleBefore:s}),d=await cn(e),l=a.semanticRuntimeAvailable?eo(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=sx({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=cx({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Ts(s,r),h=Ts(l,r),_=ux(i,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:lx(i),...ph(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:oh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:dx(i,a.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function px(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 fh(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new g("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new g("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var fx=new Set(["extensions","locks","search"]);function hx(e){let t=new Set(Rc.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(Ac));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of fx)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,a)=>r.localeCompare(a)),optionalDirs:[...n].sort((r,a)=>r.localeCompare(a)),optionalDirSet:n}}async function _x(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:a}=hx(t),o=[],s=[],c=[];for(let d of[...i,...r]){let l=be.join(e,d);c.push(...await Ne({path:l,scope:"project"})),!await Os(l)&&(a.has(d)?s.push(d):o.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function hh(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,i=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||i)&&e.full!==!0,skipDrift:(e.skipDrift===!0||i)&&e.full!==!0,skipVectors:(e.skipVectors===!0||i)&&e.full!==!0}}async function gx(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):at(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Rs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function yx(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 wx(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 vx(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 Ps=e=>e.unknown_event_count??0,Ls=e=>e.actionable_unknown_event_count??Ps(e);function bx(e,t,n,i,r,a){let o=Ps(i),s=Ls(i),c=o>0,d=s>0,l=r.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:i}:{},...l?{stale_in_progress:r}:{},...a.outcomes.length>0?{provenance_resolver_outcomes:a.outcomes}:{},...a.invalid_values.length>0?{provenance_invalid_values:a.invalid_values}:{},provenance_sample:a.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 _h(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function kx(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 Ex(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Sx(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 gh(e){let t=new Map;for(let[i,r]of Object.entries(e.remediationSources))for(let a of r)t.has(a)||t.set(a,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let r=t.get(i)??"integrity",a=Do(i)?.code??Ds(i),o=n.get(r)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=oi(i)??(a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a]),d=$s(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:a,check:r,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function xx(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 Ix(e){for(let t of e.checks){let n=Oo(e.remediationSources[t.name]);xx({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function Rx(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"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),r=new Map;for(let o of e.pendingMergeReceipts){let s=r.get(o.item_id)??[];s.push(o),r.set(o.item_id,s)}let a=[];for(let o of n){if(i.has(o))continue;let s=r.get(o);if(!(!s||s.length===0))try{await xs(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),a.push(o)}catch{}}return[...new Set(a)].sort((o,s)=>o.localeCompare(s))}function Ax(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(i=>i.startsWith("history_drift_hash_mismatch:")?!n.has(i.slice(i.indexOf(":")+1)):!0),...t.map(i=>`history_drift_merge_receipt:${i}`)].sort((i,r)=>i.localeCompare(r)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function yh(e,t={}){let n=M(process.cwd(),e.path);await ne(n);let i=Bt(n),{settings:r,warnings:a}=await el(n),o=[...new Set(a)],s=H(r,F()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=fh(t),m=await _x(n,s,c),f=px(r),p=await tx(r,{checkTelemetry:t.checkTelemetry===!0}),h=await W0(n,r,!!e.noExtensions),_=hh(t),w=[],v=await gx({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Tr(fe(r.schema),v),I=[...(await rm({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ue=>ue.startsWith("agent_guidance_")),...f,...$r(k)],C=_.skipDrift?{warnings:[]}:await Yd({pmRoot:n,settings:r,itemIds:v.map(ue=>ue.id),commandLabel:"health"}),S=await D0(n,r.history.compact_policy,await T0(n)),b=await ti(n,20,t.verboseAuthorEvents===!0),O=Ls(b),P=O>0?[`history_unknown_author_events:${O}`]:[],x=_h(await xl(n,v,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),q=await Wu(n),Se=q.warnings,_e=await nx(n),pe=_.skipIntegrity&&!l?{...Rs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await N0(n,s.type_to_folder,r.schema,r,l,v),Le=_.skipDrift?Rs("history_drift"):await ix({pmRoot:n,items:E,settings:r,typeRegistry:s,itemReadWarnings:w}),Pi=[...new Set(w)],jn=await Rx({gitWorkspaceRoot:pe.gitWorkspaceRoot,pendingMergeReceipts:pe.pendingMergeReceipts,historyDriftCheck:Le,global:e});Ax(Le,jn);let U=_.skipVectors?Rs("vectorization"):await mx(n,r,E,u,t.verboseStaleItems===!0),G=[yx(i,r,o),wx(m,c),vx(I,k),p.check,h.check,bx(v,r,S,b,x.scan,q),_e.check,pe.check,Le.check,U.check],Li=kx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Pi,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U}),Ni=Sx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Pi,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U});Ix({checks:G,remediationSources:Ni,historyDriftedCount:Ex(Le),overThresholdCount:S.over_threshold.length});let Ta=Li.filter(ue=>!$s(ue,l)),$a=gh({warnings:Li,checks:G,remediationSources:Ni,requireMergeDrivers:l}),fg=new Set($a.filter(ue=>ue.severity==="gate_failing").map(ue=>ue.check)),hg=new Set($a.map(ue=>ue.check));for(let ue of G)ue.ok=!fg.has(ue.name),hg.has(ue.name)&&(ue.status="warn");let _g={ok:Ta.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Ta.length>0?y.GENERIC_FAILURE:0},checks:G,warnings:Li,findings:$a,failed_because:Ta,generated_at:$()};return Ro(_g,t,_.summaryMode)}var Lj={buildHierarchyIntegrityWarnings:dh,buildExtensionHealthTriageSummary:lh,buildHealthFindings:gh,buildCapabilityContractMetadata:yi,buildStaleInProgressHealthSummary:_h,buildVectorizationProviderDetails:ph,collectUnknownCapabilityGuidance:gi,isAdvisoryHealthWarning:$s,isDirectory:Os,isExpectedUnmanagedExtension:As,listItemDocumentPaths:ch,normalizeEndpointForDisplay:ua,normalizeExtensionNameForMatch:Tn,parseTelemetryQueue:uh,probeTelemetryEndpointHealth:mh,projectHealthResult:Ro,resolveActionableUnknownAuthorEventCount:Ls,resolveHealthSkipPolicy:hh,resolveUnknownAuthorEventCount:Ps,resolveVectorRefreshPolicy:fh,selectStaleItemDetail:Ts,summarizeHealthCheckDetails:xo,summarizeExtensionList:ii,summarizeRecordList:Fe,summarizeStringList:W,telemetryEnvFlagEnabled:la,warningCode:Ds};(function(){try{var e=typeof window<"u"?window:typeof 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 wh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Pl(e,t).ok)return{reason:"unverified_history"};let i=ar(),r={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(i.metadata.status));i=nl(i,o.patch,a+1,o.op),n.has(String(i.metadata.status))?s||(r=["create","close","cancel","update","update_audit"].includes(o.op)&&vt(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):r={reason:"no_proven_transition"}}return r}function vh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function bh(e,t,n,i,r){let a=vh(n),o=t.filter(d=>a.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of i?o:[]){let l;try{let u=await Me(Ot(e,d.id),d.id),{body:m,...f}=d;l=wh(u,{metadata:f,body:m},a)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}s.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,r).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>r,closure_history_inspected:i,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,r),closure_timestamp_residual_truncated:c.length>r,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function kh(e,t){let n=M(process.cwd(),t.path),i=await T(n),r=fe(i.schema);await ot({pmRoot:n,settings:i,id:e.item_id,op:"update",author:z(t.author,i.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await Me(Ot(n,a.metadata.id),a.metadata.id),s=vh(r),c=wh(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new g("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",y.GENERIC_FAILURE);return a.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 Cx(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Eh(e){return`${e.item_id} ${e.link_kind}`}function Sh(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Cx(r.classification,i.classification),r.owners.set(Eh(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Eh(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.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 xh(e,t,n,i,r=40){let a=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,o=new Map(t.map(d=>[d.path,d])),s={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=Sh(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=nr(f.status,i)??f.status;i.terminal_statuses.has(p)?(u.push(f),p===i.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,a),items_truncated:d.items.length>a}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import $n from"node:fs/promises";import Dn 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 Tx(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let a;try{a=await $n.readdir(Dn.join(e,r))}catch{return}for(let o of a)for(let s of Un)if(o.toLowerCase().endsWith(s)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-s.length)});break}})),i.sort((r,a)=>r.relativePath.localeCompare(a.relativePath))}function $x(e,t){let{id:n,relativePath:i,liveItemIds:r,out:a}=e,o=$e(t);if(o){a.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=Dx(e,t);s!==null&&(s.op==="delete"&&r.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function Dx(e,t){let{id:n,relativePath:i,out:r}=e,a=null,o=!1,s=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of s){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");a=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)return r.unparseable.push({id:n,path:i,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return a}function Ns(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 Ox(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await $n.readdir(Dn.join(e,"history"))}catch{return n}for(let r of i.sort((a,o)=>a.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await $n.readFile(Dn.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ns("history stream",o)});continue}$x({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},a)}return n}function Ih(e){let t=$e(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 Px(e){let t=[],n=0,i=null;try{i=await B(Bt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Ns("configuration file",a)})}if(i!==null){n+=1;let a=Ih(i);a!==null&&t.push({path:"settings.json",detail:a})}let r;try{r=await $n.readdir(Dn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of r.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await $n.readFile(Dn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Ns("configuration file",c)});continue}let s=Ih(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function Rh(e,t,n,i={}){let r=await Tx(e,n),a=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Dn.join(e,u.relativePath);return bt(await $n.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Ox(e,a),l=await Px(e);return{item_files_on_disk:r.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,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 cc from"node:fs/promises";import{realpathSync as JI}from"node:fs";import{execFile as VI}from"node:child_process";import Ee from"node:path";import{promisify as KI}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 Lx=["metadata","resolution"],Ms=["metadata","resolution","estimates","timestamps","lifecycle"],Nx="completed";function js(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Ah(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ch(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=Ah(n.close_reason)??Nx;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${js(i)}`,gate:"resolution"})}return t}function Th(e){let t=[];for(let n of e){let i=Ah(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${js(i)}`,gate:"metadata"})}return t}function $h(e,t){return e.map(n=>{let i=Zd(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function Dh(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 Oh(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=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 ${i} ${n.item_id} --remove ${js(n.path)}`})}return t}function Ph(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new g(`--fix-scope values must not be empty. Supported values: ${Ms.join(", ")}.`,y.USAGE);return new Set(Lx)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(Ms.includes(r)){n.add(r);continue}throw new g(`Unknown --fix-scope value "${i}". Supported values: ${Ms.join(", ")}.`,y.USAGE)}return n}function Lh(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function xi(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 Mx=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function jx(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=Mx.exec(n);if(!i)return null;let r=i[1],a=r.toUpperCase(),o=r.slice(0,r.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(r.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${a}`)||d.includes(`ISSUE CODE \`${a}\``)||d.includes(`\`${a}\``)||d.includes(`[${a}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(o.toUpperCase())||l?a:null}function Nh(e){return typeof e=="string"&&e.trim().length>0}function Fx(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,i=new Map;for(let o of e){let s=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(d=>d!==s&&t.has(d)));n.set(s,c);for(let d of c){let l=i.get(d)??[];l.push(s),i.set(d,l)}}let r=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<r.length;o+=1)for(let s of i.get(r[o])??[]){let c=n.get(s);c.delete(r[o]),c.size===0&&(a.add(s),r.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function Mh(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||Nh(r.duplicate_of))continue;let a=jx(r.title,{...t,evidenceText:r.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===r.id)||o.push({id:r.id,title:r.title,parent:Nh(r.parent)?r.parent.trim():null,derivations:(r.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==r.id.toLowerCase())})}let i=[];for(let[r,a]of n){if(a.length<2)continue;let o=Fx(a);if(o.length<2)continue;let s=[...o].sort((c,d)=>c.id.localeCompare(d.id));i.push({code:r,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return i.sort((r,a)=>r.code.localeCompare(a.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 jh(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,a)=>r.localeCompare(a))){let r=t.get(i),a={};for(let o of[...r.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=r.get(o);n[i]=a}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 Fh(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Uh(e,t,n=3){let i=Number.isFinite(n)&&n>=1?Math.floor(n):3,r=new Map;for(let a of t){let o=Fh(a);if(o.length===0)continue;let s=r.get(o);s?s.push(a):r.set(o,[a])}return e.map(a=>{if(a.includes(",")||a.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:a,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(r.get(Fh(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Hh(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]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var Ux=/^[a-z][a-z0-9+.-]+:\/\//i;function Ii(e){return Ux.test(e.trim())}import Hx from"node:fs/promises";import ke from"node:path";import{glob as zx}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]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var Wx=["path","scope","note"],qx=["pattern","glob","path","scope","note"],Gx=["path"],Bx=["from","to"],Jx=new Set(["note","scope"]);function Wh(e){let t=e??"project";if(!Da.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Da.join(", ")} (default: project).`,y.USAGE);return t}function Fs(e){if(e.startsWith("```")||e.includes(`
|
|
56
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),i=n.indexOf("=");return i>=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(r=>r>=0&&r<i))?!1:n.includes("=")||Rd(e)}function Vx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Kx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Fs(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let a=e.slice(t+2,-1).trim();if(a.length>0&&Vx(a))return{path:a,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let i=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(!(i.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(r)))return{path:r,scope:"project",note:i}}function Yx(e,t){return e?e.flatMap(n=>{let i=n.trim();if(t==="doc"){let a=Kx(i);if(a!==void 0)return[a]}Ad(i,"--add",`${t} path`,Fs(i));let r=Fs(i)?Hn(n,"--add"):{path:i};if(zn(r,"--add",Wx),!r.path)throw new g(`--add requires path=<value> or a bare ${t} path`,y.USAGE);return[{path:r.path,scope:Wh(r.scope),note:r.note?.trim()||void 0}]}):[]}function Xx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--add-glob requires a glob pattern value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=Hn(n,"--add-glob");zn(i,"--add-glob",qx);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new g("--add-glob key/value form requires pattern=<glob>",y.USAGE);return{pattern:r,scope:Wh(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Zx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--remove requires a path value",y.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=Hn(n,"--remove"),r=Object.keys(i).filter(a=>Jx.has(a.toLowerCase()));if(r.length>0)throw new g(`--remove identifies a linked artifact by path only and does not accept ${r.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,y.USAGE);if(zn(i,"--remove",Gx),!i.path)throw new g("--remove key/value form requires path=<value>",y.USAGE);return i.path}return n}):[]}function Qx(e){return e?e.map(t=>{let n=Hn(t,"--migrate");zn(n,"--migrate",Bx);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new g("--migrate requires from=<value> and to=<value>",y.USAGE);return{from:i,to:r}}):[]}function Ri(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function eI(e,t,n=[]){if(e.length===0||t.length===0)return;let i=new Set(e.map(a=>Ri(a.path,n))),r=[...new Set(t.map(a=>Ri(a,n)).filter(a=>i.has(a)))].sort((a,o)=>a.localeCompare(o));if(r.length!==0)throw new g(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${r.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,y.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 gt(e){return e.split(ke.sep).join("/")}function Us(e,t,n=process.cwd()){let i=e.trim();if(Ii(i))return i;if(ke.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return gt(i.replaceAll("\\",ke.sep));let r=ke.relative(t,n);return r.startsWith(`..${ke.sep}`)||r===".."||ke.isAbsolute(r)?gt(ke.normalize(i)):gt(ke.relative(t,ke.resolve(n,i)))}async function tI(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){if(ke.resolve(n,r.pattern)===ke.resolve(n))continue;let a=ke.isAbsolute(r.pattern),o=await zx(r.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>Us(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of s)i.push({path:c,scope:r.scope,note:r.note})}return i}function nI(e,t,n){if(t===void 0)return e;if(!n)throw new g("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",y.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function iI(e){return`${e.path}::${e.scope}`}function Hs(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function zs(e){return[...new Map(e.map(t=>[iI(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function rI(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),i=[],r=[],a=[],o=[];for(let s of n){if(Ii(s)){o.push(s.trim());continue}let c=ke.isAbsolute(s)?s:ke.resolve(t,s);try{(await Hx.stat(c)).isFile()?i.push(s):a.push(s)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&yt(d)){r.push(s);continue}a.push(s)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:a,remote_references:o}}function aI(e,t,n,i){let r=0;for(let a=0;a<e.length;a+=1){let o=Ri(e[a].path,i);o!==e[a].path&&(e[a]={...e[a],path:o},r+=1)}return{adds:t.map(a=>{let o=Ri(a.path,i);return o!==a.path&&(r+=1),{...a,path:o}}),removes:n.map(a=>Ri(a,i)),count:r}}function oI(e,t,n,i){let r=zs(e);for(let a of t){let o=r.findIndex(s=>s.path===a.path&&s.scope===a.scope);o<0?r.push(a):a.note!==void 0&&(r[o]={...r[o],note:a.note})}if(n.length>0)for(let a=r.length-1;a>=0;a-=1)n.includes(r[a].path)&&r.splice(a,1);return i?r:Hs(r)}async function zh(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 rI(t,e.workspaceRoot):void 0}}async function ma(e,t,n,i){let{metadataKey:r}=i,a=Cd(),o=M(process.cwd(),n.path),s=Be(o),c=process.cwd();await ne(o);let d=await T(o),l=H(d,F()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),p=await a.resolveList(t.migrate,"--migrate"),h=Yx(u,i.bareNoun).map(P=>({...P,path:Us(P.path,s,c)})),_=Xx(m),w=await tI(_,s,c),v=nI([...h,...w],t.note,h.length>0||_.length>0),E=Zx(f).map(P=>Us(P,s,c)),k=Qx(p);if(eI(v,E,k),!(v.length>0||E.length>0||k.length>0)){let P=await ge(o,e,d.id_prefix,d.item_format,l.type_to_folder);if(!P)throw new g(`Item ${e} not found`,y.NOT_FOUND);let x=(await ye(P,{schema:d.schema})).document.metadata[r]??[];return zh({id:P.id,artifacts:x,changed:!1,options:t,workspaceRoot:s})}let I=z(t.author,d.author_default),C=await ot({pmRoot:o,settings:d,id:e,op:i.op,author:I,message:t.message,force:t.force,skipNoop:!0,mutate(P){let x=P.metadata,q=x[r]??[],Se=[...q],_e=aI(Se,v,E,k),pe=oI(Se,_e.adds,_e.removes,i.supportsAppendStable&&t.appendStable===!0);pe.length>0?x[r]=pe:delete x[r];let Le=!Fc(q,pe);return{changedFields:Le?[r]:[],warnings:Le&&_e.count>0?[`path_migrations_applied:${_e.count}`]:[]}}}),S=C.item[r]??[],b=C.warnings.find(P=>P.startsWith("path_migrations_applied:")),O=b?Number(b.slice(24)):0;return zh({id:C.item.id,artifacts:S,changed:C.changedFields.includes(r),migrationsApplied:O,options:t,workspaceRoot:s})}function pa(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=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]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function qh(e,t,n){let i=await ma(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return pa(i,"docs")}import Gh from"node:fs/promises";import Pe 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 sI=32768;function Ws(e){return gt(Pe.normalize(e))}async function fa(e){try{return await Gh.realpath(e)}catch{return Pe.resolve(e)}}function On(e,t){let n=Pe.isAbsolute(e.path)?Pe.resolve(e.path):Pe.resolve(t,e.path);return`${Ws(n)}::${e.scope}`}function ha(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>ha(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))ha(r,t?`${t}.${i}`:i,n)}function cI(e){let t=[];return ha(e.metadata,"metadata",t),ha(e.body,"body",t),t}function dI(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 lI(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{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 r of e){let a=new Set,o=r.value.slice(0,sI);for(let[s,c]of[[n,r.value],[i,o]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=dI(d[0]);!l||a.has(l)||(a.add(l),t.push({field:r.field,value:l}))}}}return t}async function uI(e,t,n=t){let i=Pe.isAbsolute(e)?Pe.resolve(e):Pe.resolve(n,e),r;try{r=await Gh.stat(i)}catch{return}if(!r.isFile())return;let[a,o]=await Promise.all([fa(t),fa(i)]);if(me(a,o)){let s=Pe.relative(a,o);return!s||s.startsWith("..")||Pe.isAbsolute(s)?void 0:{path:Ws(s),scope:"project"}}return{path:Ws(i),scope:"global"}}async function mI(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>On(c,t))),r=new Map,a=lI(cI(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await uI(c,t,n))}));let s=a.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of s){if(!d)continue;let l=On(d,t),u=r.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,r.set(l,u)}return[...r.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:i.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 Bh(e,t,n){let i=await ma(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return pa(i,"files")}async function pI(e,t){let n=await fa(t),i=await Promise.all(e.map(async a=>{let o=a.trim();if(!o)throw new g("Files lookup paths must not be empty.",y.USAGE);if(!Pe.isAbsolute(o))return gt(o);let s=await fa(o);return me(n,s)?gt(Pe.relative(n,s)):gt(s)})),r=[...new Set(i)].sort((a,o)=>a.localeCompare(o));if(r.length===0)throw new g("Files lookup requires at least one path.",y.USAGE);return r}function fI(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new g(`Files lookup ${i} must be a non-negative integer.`,y.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 Jh(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Vh(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function hI(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(gt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(Vh)}async function _I(e){if(e.explain)return Au({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 gI(e){if([e.strictRead,e.noTruncate,e.explain,fd()].includes(!0))return null;let t=await mr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?dl({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function yI(e){let t=[],n=await pr(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=hI({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&r.length>0)throw new g(`Files lookup could not read every item: ${r.join("; ")}`,y.GENERIC_FAILURE);let a=await _I({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),o=(a?[...i].sort((s,c)=>{let d=a.explanations.get(c.item.id).score-a.explanations.get(s.item.id).score;return d!==0?d:Vh(s,c)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:o.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+o.length<i.length,truncated:e.offset+o.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:o.map(s=>({item:Jh(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function KF(e,t){let n=M(process.cwd(),t.path),i=Be(n);await ne(n);let r=await pI(e.paths,i);if(e.lineRange&&r.length!==1)throw new g("Files lookup line attribution requires exactly one source path.",y.USAGE);let a=await T(n),o=H(a,F()),{offset:s,limit:c}=fI(e),d=await gI({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:r,total:d.total,count:d.matches.length,offset:s,limit:c,has_more:s+d.matches.length<d.total,truncated:s+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:Jh(l.item),files:l.files}))}:yI({pmRoot:n,settings:a,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function YF(e,t,n){let i=M(process.cwd(),n.path),r=Be(i);await ne(i);let a=await T(i),o=H(a,F()),s=await ge(i,e,a.id_prefix,a.item_format,o.type_to_folder);if(!s)throw new g(`Item ${e} not found`,y.NOT_FOUND);let c=await ye(s,{schema:a.schema}),d=await mI(c.document,r,process.cwd()),l=d.filter(b=>b.status==="addable"),u=d.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let b=c.document.metadata.files??[];return{id:s.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let p=z(t.author,a.author_default),h=l.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],w=new Set,v=await ot({pmRoot:i,settings:a,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let O=[...b.metadata.files??[]],P=new Set(O.map(Se=>On(Se,r)));_=[],w.clear();for(let[Se,_e]of h.entries()){let pe=On(_e,r);P.has(pe)||(O.push(_e),P.add(pe),_.push(_e),w.add(Se))}let x=zs(O),q=t.appendStable?x:Hs(x);return q.length>0?b.metadata.files=q:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==h.length?[`files_discover_skipped_existing:${h.length-_.length}`]:[]}}}),E=v.item.files??[],k=new Set(_.map(b=>On(b,r))),I=E.filter(b=>k.has(On(b,r))),C=l.filter((b,O)=>!w.has(O)),S=[...u,...C];return{id:v.item.id,files:E,changed:I.length>0,apply:!0,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:I.length,skipped_existing_count:S.length,candidates:d,added:I,skipped_existing:S}}import{readFileSync as wI}from"node:fs";import _a 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]="597a781e-a00d-5083-8d57-3fae870f9ccd")}catch{}})();var vI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),qs=new Set(["--pm-path","--path","--author"]),bI={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"])},kI=new Set(["-p","--package"]),EI=new Set(["-c","--call"]),SI=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),xI=new Set(["-C","--prefix","--userconfig","--cache"]),eU=new Set(["--cwd"]),tU=new Set(["--cwd"]),II=new Set(["exec","x"]),nU=new Set(["run","run-script"]),iU=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function RI(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function AI(e,t=process.cwd()){let n=CI(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[i,...r]=n;if(Kh(i)||Yh(i,t))return r;if(i==="node"&&r[0]&&Yh(r[0],t))return r.slice(1);let a=i==="npx"||i==="bunx"?Gs(r):i==="pnpm"?DI(r):i==="npm"?OI(r):null;return a&&(Kh(a.command)||$I(a.command))?a.args:null}var Xh=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let s of RI(a)){let c=AI(s),d=c?PI(c):null,l=d&&vI.has(d.subcommand)?LI(d.remaining,bI[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(l)}return[...o].sort((s,c)=>s.localeCompare(c))};function CI(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 rU(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(qs.has(n)){t+=2;continue}t+=1;continue}return n}}function Kh(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function TI(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function $I(e){let t=TI(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Yh(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 i=_a.resolve(t,e);try{return JSON.parse(wI(_a.join(_a.dirname(_a.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Gs(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let a=r[1];return a?{command:a,args:e.slice(t+1)}:null}if(EI.has(i)){t+=1;break}t+=kI.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Zh(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function DI(e){let t=Zh(e,SI);return t?.subcommand!=="dlx"?null:Gs(t.args)}function OI(e){let t=Zh(e,xI);return!t||!II.has(t.subcommand)?null:Gs(t.args)}function PI(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(qs.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function LI(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(qs.has(i)||t.has(i))&&(n+=1)}}import{execFile as NI}from"node:child_process";import{readFile as MI}from"node:fs/promises";import e_ from"node:path";import{promisify as jI}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 FI=jI(NI),Bs=1,UI="linked-test-trust.json";function Js(e){return e_.join(jc(e),UI)}function Qh(){return{version:Bs,acknowledged:{}}}async function Vs(e){try{let t=JSON.parse(await MI(Js(e),"utf8"));return t.version!==Bs||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Qh():{version:Bs,acknowledged:t.acknowledged}}catch{return Qh()}}async function Ks(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 FI("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),i=n.trim();return i.length===0?void 0:i}catch{return}}function Ys(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function HI(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&gd(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Ai(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function zI(e,t,n,i){return e?.map(r=>r.command&&!r.provenance?{...r,provenance:{author:t,created_at:n,source_kind:"local_mutation",...i?{source_ref:i}:{}}}:r)}async function hU(e,t,n){if(!e||e.length===0)return e;for(let r of e)Td(r);let i=Ys();return zI(e,t,n,await Ks(i))}function t_(e){return xe(A({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 _U(e,t,n){let i=await Vs(e);return n_(t,n,i)}function n_(e,t,n){let i=t_(e),r=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:i,trusted:!0,reason:"legacy"};let a=Object.hasOwn(n.acknowledged,i);return e.provenance_invalid===!0||!HI(e.provenance)?a?{fingerprint:i,trusted:!0,reason:"acknowledged",...Ai(void 0,t)}:{fingerprint:i,trusted:!1,reason:"invalid_provenance",...Ai(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r===void 0?{fingerprint:i,trusted:!0,reason:"local_mutation",...Ai(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r!==void 0&&r===t?{fingerprint:i,trusted:!0,reason:"local_source_ref",source_ref:r,current_source_ref:t}:a?{fingerprint:i,trusted:!0,reason:"acknowledged",...Ai(r,t)}:{fingerprint:i,trusted:!1,reason:"foreign_source_ref",...Ai(r,t)}}async function i_(e,t,n){let i=await Vs(e);return t.map(r=>n_(r,n,i))}async function gU(e,t,n){let i=await Vs(e),r=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(t_);for(let a of r)i.acknowledged[a]={acknowledged_at:n};return await Fn(e_.dirname(Js(e))),await Z(Js(e),`${JSON.stringify(i,null,2)}
|
|
57
|
+
`),{acknowledged:r.length,fingerprints: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]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function ga(e){return e.includeBody?at(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):pr(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 WI=5;async function qI(e,t){let n=t.hashMismatches.filter(a=>a!==te);if(n.length===0)return;let i=await T(e),r=H(i,F());for(let a of n){let o=await re(e,a,i.locks.ttl_seconds,"history-drift-read",!1,!0,i.locks.wait_ms);try{let s=await ge(e,a,i.id_prefix,i.item_format,r.type_to_folder);if(s===null)throw new g(`Item ${a} not found`,y.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await ye(s,{schema:i.schema});if(c.metadata.id!==a)throw new g(`Item identity changed while validating ${a}`,y.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await pm(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==a),...d[u].filter(m=>m===a)].sort((m,f)=>m.localeCompare(f));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==a),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===a)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function ya(e,t,n){let i=await Ht(e,t);await qI(e,i);let r=[["validate_history_drift_missing_streams",i.missingStreams.length],["validate_history_drift_unreadable_streams",i.unreadableStreams.length],["validate_history_drift_hash_mismatches",i.hashMismatches.length],["validate_history_drift_chain_mismatches",i.chainMismatches.length],["validate_history_drift_version_skews",i.versionSkews.length],["validate_history_drift_workspace_state_mismatches",i.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",i.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",i.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),a=n?Number.POSITIVE_INFINITY:WI,o=i.driftedItems.slice(0,a),s=i.identityDiscontinuities??[];return{check:{name:"history_drift",status:s.length>0?"error":r.length===0?"ok":"warn",ok:s.length===0&&r.length===0,details:{identity_discontinuities:s.slice(0,a),identity_discontinuities_count:s.length,identity_discontinuities_truncated:s.length>a,checked_items:t.length,drifted_items_count:i.driftedItems.length,drifted_items:o,drifted_items_truncated:o.length<i.driftedItems.length,counts:{missing_streams:i.missingStreams.length,unreadable_streams:i.unreadableStreams.length,hash_mismatches:i.hashMismatches.length,chain_mismatches:i.chainMismatches.length,version_skews:i.versionSkews.length,workspace_state_mismatches:i.workspaceStateMismatches.length,workspace_state_missing:i.workspaceStateMissing.length,workspace_state_unreadable:i.workspaceStateUnreadable.length},workspace_state_mismatches:i.workspaceStateMismatches,workspace_state_missing:i.workspaceStateMissing,workspace_state_unreadable:i.workspaceStateUnreadable,version_skews:i.versionSkews.slice(0,a)}},warnings: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]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function wa(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],a=new Set([n]),o=s=>{for(let c of(t.get(s)??[]).filter(d=>i.has(d))){if(c===n&&r.length>1)return r.push(n),!0;if(!a.has(c)){if(a.add(c),r.push(c),o(c))return!0;r.pop(),a.delete(c)}}return!1};return o(n)?[...r]:[...e,n]}function GI(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function BI(e,t,n,i){for(let r of e.dependencies??[]){if(typeof r!="object"||r===null||typeof r.id!="string")continue;let a=i.resolve(r.kind);if(!a?.hierarchy)continue;let o=n.get(r.id.toLowerCase());o&&(a.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function Xs(e,t=Jn()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),i=new Map(e.map(r=>[r.id,[]]));for(let r of[...e].sort((a,o)=>a.id.localeCompare(o.id))){let a=i.get(r.id),o=GI(r.parent,n);o&&a.push(o),BI(r,i,n,t)}for(let[r,a]of i)i.set(r,[...new Set(a)].sort());return i}function Zs(e,t,n=Jn()){let i=hr(e,o=>t?od(o,t):o==="closed"||o==="canceled",n),r=Xs(e,n),a=i.cycles.map(o=>o.item_ids);return{cycle_count:a.length,active_cycle_count:i.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:i.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(a.flat())].sort(),cycle_sample_paths:a.map(o=>wa(o,r).join("->")),cardinality_violation_count:i.cardinality_violations.length,active_cardinality_violation_count:i.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:i.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:i.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:i.divergences.length,active_parent_divergence_count:i.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:i.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:i.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 $t(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Qs(e){return $t(e).replace(/\/+$/,"")}function We(e){let t=Y(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function ec(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]="9ef196b2-3eef-5bac-b949-bcb3e947c44d")}catch{}})();var YI=["src","tests","docs"],XI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],ZI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),QI=["resolution","expected_result","actual_result"],eR=["default","tracked-all","tracked-all-strict"],r_=["core","strict","custom"],ka=["off","warn","error"],ic=["author","acceptance_criteria","estimated_minutes","close_reason"],s_=[...ic,"reviewer","risk","confidence","sprint","release"],rc=Array.from(new Set(s_)),tR={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"},nR={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"},iR={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"},rR={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"},aR={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"},oR=32*1024*1024,sR=1e4,ac=40,qe=5,cR=4096,dR=255,lR=KI(VI);function c_(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||i===!1&&n.endsWith("_truncated")||(t[n]=typeof i=="object"&&i!==null?c_(i):i);return t}function uR(e){return{...e,checks:e.checks.map(t=>({...t,details:c_(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 Sa(e,t){return nr(e,t)??e}function Ci(e,t){return t.terminal_statuses.has(Sa(e,t))}function Dt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function va(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function mR(e){let t=Dt(Cc),n={blocked_reason:Dt(Fi.blocked_reason),resolution:Dt(Fi.resolution),actual_result:Dt(Fi.actual_result)},i=Dt(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:Dt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Dt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Dt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:va(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:va(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:va(r.resolution,n.resolution)?"default":"settings",actual_result:va(r.actual_result,n.actual_result)?"default":"settings"}}}function d_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(r_.includes(t))return t;throw new g(`Unknown --metadata-profile value "${e}". Supported values: ${r_.join(", ")}.`,y.USAGE)}function l_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ka.includes(t))return t;throw new g(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ka.join(", ")}.`,y.USAGE)}function u_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ka.includes(t))return t;throw new g(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ka.join(", ")}.`,y.USAGE)}function pR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>tR[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function fR(e,t,n){let i=pR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...ic],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...s_],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...ic],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var hR=new Set(["acceptance_criteria","estimated_minutes"]);function m_(e,t,n,i){return!i&&hR.has(t)&&Ci(e.status,n)?!1:t==="author"?!Y(e.author):t==="acceptance_criteria"?!Y(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Sa(e.status,n)===n.close_status&&!Y(e.close_reason):t==="reviewer"?!Y(e.reviewer):t==="risk"?!Y(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!Y(e.confidence):t==="sprint"?!Y(e.sprint):!Y(e.release)}function p_(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 g(`Unknown --scan-mode value "${e}". Supported values: ${eR.join(", ")}.`,y.USAGE)}function f_(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ee.resolve(t);let n=Ee.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ee.dirname(Ee.dirname(n));let i=Ee.resolve(process.cwd()),r=a_(n),a=a_(i),o=Ee.relative(r,a);return o.length===0||!o.startsWith("..")&&!Ee.isAbsolute(o)?n:i}function a_(e){try{return JI.native(e)}catch{return Ee.resolve(e)}}function _R(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function dc(e,t,n){let i=t.length>0?Ee.join(e,t):e,r;try{r=await cc.readdir(i,{withFileTypes:!0})}catch(a){if(j(a))return;throw a}for(let a of r){if(a.name.startsWith("."))continue;let o=t.length>0?Ee.join(t,a.name):a.name;if(a.isDirectory()){if(ZI.has(a.name))continue;await dc(e,o,n);continue}a.isFile()&&n.push($t(o))}}async function oc(e){let t=[];for(let n of YI)await dc(e,n,t);for(let n of XI){let i=Ee.join(e,n);try{(await cc.stat(i)).isFile()&&t.push($t(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function h_(e){try{let{stdout:t}=await lR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:oR,windowsHide:!0,timeout:sR}),n=t.split("\0").map(i=>$t(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function gR(e,t){let n=new Set,i=Qs(Ic);i.length>0&&n.add(i);let r=Qs(Ee.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((a,o)=>a.localeCompare(o))}function o_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function yR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await h_(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await oc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await oc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ee(e,t=qe){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function qt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ee(e,ac);return{values:n.values,truncated:n.truncated,total:e.length}}var wR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},vR={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function bR(e){let t=e.missing_fields.map(n=>`${wR[n]} "${vR[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function __(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):ym(t);if(r.length===0)return;let a=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...a?{fix_hints_truncated:!0}:{}}}function g_(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 kR="validate_metadata_duplicate_issue_codes";function y_(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:qe,i=e.slice(0,n);return{rows:i.map(r=>({code:r.code,count:r.count,ids:r.ids,titles:r.titles,remediation_hint:`Items ${r.ids.join(", ")} share issue code "${r.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${kR}:${e.length}`]}}function ER(e,t,n){let i=Object.fromEntries(rc.map(r=>[r,[]]));for(let r of e)for(let a of rc)m_(r,a,t,n)&&i[a].push(r.id);return i}function SR(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let a=t[r];a.length>0&&i.push(`${nR[r]}:${a.length}`)}return i.push(...n),i}function w_(e,t){let n={};for(let i of e.required_fields){let r=t[i],a=r?r.length:0,o=iR[i];n[o]=a}return n}function v_(e,t,n){let i=[];for(let r of e.required_fields){let a=t[r];if(a)for(let o of a){let s=n.get(o)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";i.push({item_type:c,field:r})}}return i}function xR(e,t,n,i){for(let r of t.required_fields){let a=n[r];if(!a||a.length===0)continue;let o=rR[r],s=aR[r];if(!o||!s)continue;let c=ee(a,i?a.length:qe);e[o]=c.values,e[s]=c.truncated}}function b_(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:Y(n.get(r)?.resolution)})):[]}function k_(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:Y(n.get(r)?.type)})):[]}function IR(e,t,n,i,r){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=ER(e,n,o),c=Mh(e,{configuredPrefixes:r}),d=y_(c,i),l=SR(t,s,d.warnings),u=w_(t,s),m=v_(t,s,a),f=jh(m),p={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:[...rc],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),xR(p,t,s,i);let h=b_(t,s,a),_=k_(t,s,a);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:_}}function RR(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(Sa(m.status,t))),a=[],o=[];for(let m of r){let f=QI.filter(p=>!Y(m[p]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:Y(m.close_reason)}))}let s=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:qe,d=ee(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=a.map(m=>bR(m)),u=ee(l,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_closed_items:r.length,missing_resolution_items:a.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:s,resolutionBackfillRows:o}}function E_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S_(e,t="pm",n=Dc()){let i=new Set(e.map(a=>a.id)),r=[...e].sort((a,o)=>a.id.localeCompare(o.id));return new Map(r.map(a=>{let o=new Set,s=We(a.blocked_by);s&&i.has(s)&&o.add(s),(a.dependencies??[]).filter(d=>{let l=We(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>We(d.id)).filter(d=>d!==void 0&&i.has(d)).forEach(d=>o.add(d));let c=We(a.definition_of_ready);return I_(c??"",t).filter(d=>i.has(d)).forEach(d=>o.add(d)),[a.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function x_(e,t,n){let i=Tl(e,n?l=>Ci(l,n):void 0),r=i.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),a=i.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:qe,s=ee(r,o),c=ee(a,o),d=ee(i.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:r.length===0?"ok":"warn",ok:r.length===0,details:{checked_items:e.length,dangling_reference_count:r.length+a.length,active_dangling_reference_count:r.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.truncated,legacy_terminal_dangling_reference_count:a.length,legacy_closed_dangling_reference_count:i.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:i.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function I_(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${E_(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,a)=>r.localeCompare(a))}function R_(e){let t=0,n=new Map,i=new Map,r=[],a=new Set,o=[],s=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),a.add(d);for(let u of e.get(d)??[])n.has(u)?a.has(u)&&i.set(d,Math.min(i.get(d),n.get(u))):(s(u),i.set(d,Math.min(i.get(d),i.get(u))));if(i.get(d)!==n.get(d))return;let l=[];for(;r.length>0;){let u=r.pop();if(a.delete(u),l.push(u),u===d)break}l.sort((u,m)=>u.localeCompare(m)),o.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||s(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 A_(e,t="pm"){let n=S_(e,t),i=R_(n),r=[...new Set(i.flat())].sort((o,s)=>o.localeCompare(s)),a=i.map(o=>wa(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:a}}function C_(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 Ea(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function T_(e,t){let n=Ea(e).split("/").filter(Boolean),i=Ea(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function AR(e,t){let n=Ea(t),i=Ea(e),r=t.endsWith("/")?t:`${t}/`,a=e.startsWith(r),o=n.length>0&&n===i,s=T_(e,t);return!a&&!o&&s===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function CR(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function TR(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(a=>(i==="docs"?a.docs??[]:a.files??[]).map(o=>({item:a,link:o}))).forEach(({item:a,link:o})=>{if(o.scope!=="project")return;let s=$t(o.path);if(s.length===0||s===e)return;let c=AR(e,s);c!==null&&CR(r,a,c.score)&&(r={item:a,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function $_(e,t){return e.map(n=>{let i=C_(n),r=i==="docs_unowned"?"docs":"files",a=TR(n,i,t),o=a?.id??"<id>";return{path:n,classification:i,owner_candidate:a,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function D_(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function $R(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=We(e[n]);return r?i.some(a=>r.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function DR(e,t,n,i,r){let a=We(t.parent),o=a?n.get(i.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Ci(o.status,r)}}function OR(e,t,n,i){let r=We(e.blocked_by),a=We(e.blocked_reason),o=a?.toLowerCase(),s=Sa(e.status,n),c=[];return t.has(s)?(!r&&!a&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function PR(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Ci(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=$R(c,i);d.length>0&&s.closureLikeRows.push({id:c.id,fields:d});let l=We(c.parent),u=l?r.get(a.get(l.toLowerCase())??l):void 0;if(u&&Ci(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(DR(c,u,r,a,n))),t){let m=OR(c,o,n,i);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function LR(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 ba(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function tc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function NR(e,t,n,i,r){let a=[];e.closureLikeRows.length>0&&a.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&a.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&a.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=ba("validate_lifecycle_dependency_cycles",n,r.dependencyCycles),s=ba("validate_hierarchy_parent_cycle",i,r.activeHierarchyCycles),c=ba("validate_hierarchy_cardinality_violation",i,r.activeHierarchyCardinality),d=ba("validate_hierarchy_parent_divergence",i,r.activeHierarchyDivergence),l=tc("validate_legacy_hierarchy_parent_cycle",i,r.legacyHierarchyCycles),u=tc("validate_legacy_hierarchy_cardinality_violation",i,r.legacyHierarchyCardinality),m=tc("validate_legacy_hierarchy_parent_divergence",i,r.legacyHierarchyDivergence);return[...a,...o?[o]:[],...s?[s]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function O_(e){let t=$t(e);return t.length>cR||t.split(/[\\/]/).some(n=>n.length>dR)}async function MR(e,t){let n=Ee.isAbsolute(t)?t:Ee.resolve(e,t);if(O_(n))return!1;try{let i=await cc.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return _R(i,["ENOENT","ENOTDIR"])}}async function jR(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(a=>({item:r,artifact:a,link_kind:"files"})),...(r.docs??[]).map(a=>({item:r,artifact:a,link_kind:"docs"}))]);for(let{item:r,artifact:a,link_kind:o}of i){if(a.scope!=="project")continue;if(Ii(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=$t(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await MR(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:r.id,path:s,link_kind:o})))}return n}function FR(e,t,n,i,r,a){let o=i==="tracked-all-strict",s=o&&!r,c=r||o,d=c?[]:gR(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>o_(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!o_(f,d)),m={};if(l.length>0){let f=qt(l,a);m.pm_internals={count:l.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function P_(e,t,n,i,r,a,o,s="pm"){let c=PR(e,t,r,a);LR(c);let d=A_(c.activeItems,s),l=Zs(e,r),u=Tr(r,e,o?Number.POSITIVE_INFINITY:qe),m=[...NR(c,t,n,i,{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}),...$r(u)],f=o?Number.POSITIVE_INFINITY:qe,p=ee(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=ee(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),_=ee(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),w=ee(d.cycle_item_ids,f),v=ee(d.cycle_sample_paths,f),E=ee(l.cycle_item_ids,f),k=ee(l.cycle_sample_paths,f),I=ee(l.cardinality_violation_rows,f),C=ee(l.parent_divergence_rows,f),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&i==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.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:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:_.values,stale_blocker_rows_truncated:_.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:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:i,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:E.values,parent_cycle_item_ids_truncated:E.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.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:I.values,hierarchy_cardinality_violation_rows_truncated:I.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:C.values,hierarchy_parent_divergence_rows_truncated:C.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function L_(e,t,n,i,r,a,o=fe(Tc.schema)){let s=await jR(e,t),c=new Map(e.map(x=>[x.id,x])),d=[...new Set(s.missingLinkedPaths)].sort((x,q)=>x.localeCompare(q)),l=await yR(t,i),u=FR(l,n,t,i,r,a),m=u.candidateFiles.filter(x=>!s.linkedProjectPaths.has(x)),f=$_(m,e),p=Uh(d,u.candidateFiles),h=new Map(p.map(x=>[x.path,x.classification])),_=p.filter(x=>x.classification==="moved").length,w=s.staleLinkRows.map(x=>({...x,classification:h.get(x.path)??"deleted"})).sort((x,q)=>x.item_id.localeCompare(q.item_id)||x.path.localeCompare(q.path)||x.link_kind.localeCompare(q.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let E=[...s.remoteLinkedPaths].sort((x,q)=>x.localeCompare(q)),k=qt(E,a),I=qt(d,a),C=qt(m,a),S=qt(f.map(x=>`${x.path}:${x.classification}:owner_candidate=${x.owner_candidate?.id??"unowned"}`),a),b=a?f:qt(D_(f),!1).values,O=qt(Hh(p),a),P=xh(w,p,x=>c.get(x),o,a?1/0:ac);return P.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${P.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.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:a?"full":"summary",file_list_summary_limit:ac,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:r,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:s.linkedProjectPaths.size,remote_linked_paths_count:E.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.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:I.total,missing_linked_paths:I.values,missing_linked_paths_truncated:I.truncated,missing_linked_paths_moved_count:_,missing_linked_paths_deleted_count:p.filter(x=>x.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(x=>x.classification==="malformed").length,missing_linked_path_classifications:O.values,missing_linked_path_classifications_truncated:O.truncated,...P,orphaned_paths_count:m.length,orphaned_paths_total:C.total,orphaned_paths:C.values,orphaned_paths_truncated:C.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function UR(e,t){let n=[];return e.forEach(({item:i,linkedTest:r},a)=>{let o=t[a];if(o.trusted)return;let s=ec(r.command??"");n.push(`${i.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function N_(e,t,n,i){let r=new Set(e.map(I=>I.id.toLowerCase())),a=0,o=0,s=new Set,c=[],d=e.flatMap(I=>(I.tests??[]).map(C=>({item:I,linkedTest:C}))),l=await Ks(Ys()),u=await i_(i,d.map(({linkedTest:I})=>I),l),m=UR(d,u);for(let{item:I,linkedTest:C}of d){if(typeof C.command!="string"||C.command.trim().length===0)continue;a+=1;let S=Xh(C.command,t);if(S.length!==0){o+=S.length;for(let b of S)s.add(b),r.has(b.toLowerCase())||c.push(`${I.id}:${b}:${ec(C.command)}`)}}let f=[...new Set(c)].sort((I,C)=>I.localeCompare(C)),p=[...new Set(f.map(I=>I.split(":")[1]??""))].filter(I=>I.length>0).sort((I,C)=>I.localeCompare(C)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let _=n?Number.POSITIVE_INFINITY:qe,w=ee(f,_),v=ee(p,_),E=ee([...s].sort((I,C)=>I.localeCompare(C)),_),k=ee(m,_);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:a,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:E.values,unique_referenced_pm_ids_truncated:E.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:k.values,untrusted_linked_tests_truncated:k.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function HR(e,t){let n=tr(e.map(c=>({ref:c.id,version:er(c)})),Wn,Qi),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:qe,a=ee(n.outdated,r),o=ee(n.ahead,r),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:Wn,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var sc="pm validate auto-fix";async function M_(e,t,n){switch(e.kind){case"set_closed_at":await kh(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:sc};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new g("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",y.USAGE);await n.runUpdate(e.item_id,i,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 nc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function j_(e,t,n){let i=[],r=[],a=new Map;for(let o of e.filter(s=>nc(s)===null))try{await M_(o,t,n),i.push(o)}catch(s){r.push({fix:o,error:s})}for(let o of e.filter(s=>nc(s)!==null)){let s=nc(o),c=a.get(s);c?c.push(o):a.set(s,[o])}for(let o of a.values()){let s=o[0];if(!s)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{s.kind==="prune_file_link"?await Bh(s.item_id,{remove:c,message:sc},t):await qh(s.item_id,{remove:c,message:sc},t),i.push(...o)}catch(d){r.push(...o.map(l=>({fix:l,error:d})))}}return{applied:i,failed:r}}var AH={applyValidateFix:M_,applyValidateFixes:j_,attachValidateFixHints:__,buildCommandReferencesCheck:N_,buildDependencyReferencesCheck:x_,buildCloseReasonBackfillRows:b_,buildFilesCheck:L_,buildLifecycleCheck:P_,buildLifecycleDependencyGraph:S_,buildLifecycleParentGraph:Xs,buildEstimateBackfillRows:k_,buildMetadataCounts:w_,buildMissingFieldOccurrences:v_,buildOrphanedPathRows:$_,classifyOrphanedPath:C_,collectDefaultProjectFileCandidates:oc,collectTrackedGitFileCandidates:h_,detectLifecycleDependencyCycles:A_,detectLifecycleParentCycles:Zs,escapeRegExp:E_,extractItemIds:I_,findLifecycleDependencyCycleComponents:R_,isMetadataFieldMissing:m_,linkedArtifactPathExceedsFilesystemLimits:O_,listFilesRecursive:dc,resolveDependencyCycleSeverity:l_,resolveParentCycleSeverity:u_,resolveFileScanMode:p_,resolveLifecycleDependencyCycleSamplePath:wa,resolveRequestedChecks:g_,resolveValidateMetadataProfile:d_,resolveWorkspaceRoot:f_,sharedDirectoryPrefixLength:T_,summarizeOrphanedPathRows:D_,summarizeDuplicateIssueCodes:y_,toMeaningfulString:We};function zR(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function WR(e,t,n,i){let r=await Rh(e,new Set(t.map(_=>_.id)),n,{schema:i.schema,extensionFieldNames:Gt(F())}),a=[];r.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=a.length,s=await Xr(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await ln(e,dn(i));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await St(e),l=d===null?null:await un(d);l!==null&&l.status!=="ok"&&a.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await ft(d??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Cn(m);f.length>0&&a.push(`validate_merge_decisions_unreviewed:${f.length}`),zR(a,u.invalid_evidence_count);let h=o>0?"error":a.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...r,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),lossless_merge_receipt_count:p.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(p.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:a}}function nt(e,t,n){n&&__(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function qR(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let r=await fu(e.pmRoot,e.items,i?1/0:qe,e.sourceIncomplete);nt(t,r,n)}if(e.requestedChecks.has("metadata")){let r=IR(e.items,e.metadataPolicy,e.statusRegistry,i,[e.settings.id_prefix]);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows;let a=await bh(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,i?1/0:qe);t.closureTimestampFixes=a.fixes,Object.assign(r.check.details,a.details),r.warnings.push(...a.warnings),r.check.ok=r.warnings.length===0,r.check.status=r.check.ok?"ok":"warn",nt(t,r,n)}if(e.requestedChecks.has("resolution")){let r=RR(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,nt(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=P_(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,nt(t,r,n),nt(t,x_(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await L_(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=r.staleLinkPruneRows,nt(t,r,n)}return e.requestedChecks.has("command_references")&&nt(t,await N_(e.items,e.settings.id_prefix,i,e.pmRoot),n),e.requestedChecks.has("history_drift")&&nt(t,await ya(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&nt(t,HR(e.items,i),n),e.requestedChecks.has("storage_integrity")&&nt(t,await WR(e.pmRoot,e.items,H(e.settings,F()).type_to_folder,e.settings),n),t}function GR(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...t.closureTimestampFixes),i.push(...Th(t.closeReasonBackfillRows)),i.push(...Ch(t.resolutionBackfillRows)),i.push(...$h(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...Dh(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Oh(t.staleLinkPruneRows)),i}async function BR(e,t,n,i,r,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=GR(e,t,n),{applicable:s,gated:c}=Lh(o,i),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await j_(s,r,a);l.push(...m.applied.map(xi)),u.push(...m.failed.map(({fix:f,error:p})=>({...xi(f),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(xi),applied_fixes:l,gated_fixes:c.map(m=>({...xi(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function F_(e,t,n={}){hd(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new g("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",y.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new g("--fix-scope requires --auto-fix.",y.USAGE);let r=Ph(e.fixScope),a=M(process.cwd(),t.path);await ne(a);let o=await T(a),s=fe(o.schema),c=H(o,F()),d=g_(e),l=[],u=await ga({includeBody:["history_drift","metadata","completeness"].some(O=>d.has(O)),pmRoot:a,settings:o,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let O=await ti(a);O.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${O.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=d_(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=fR(p,f,o.validation.metadata_required_fields),_=mR(o),w=l_(e.dependencyCycleSeverity),v=u_(e.parentCycleSeverity),E=p_(e.scanMode),k=f_(a),I=await qR({requestedChecks:d,options:e,global:t,pmRoot:a,workspaceRoot:k,settings:o,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:_,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:E,initialWarnings:[...new Set(l)],sourceIncomplete:m}),C=i?await BR(e,I,o,r,t,n):void 0,S=[...new Set(I.warnings)].sort((O,P)=>O.localeCompare(P)),b={ok:!I.checks.some(O=>O.status==="error"),has_warnings:S.length>0,checks:I.checks,warnings:S,...C!==void 0?{fixes:C}:{},generated_at:$(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...uR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as JR}from"node:child_process";import{promisify as VR}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 KR=VR(JR),YR=16,XR=3e4;function ZR(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(i=>typeof i=="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 QR(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let i=t.parameters??{},r=n.parameters??{};for(let a of Object.entries(r).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(i,a))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${a}`);for(let[a,o]of Object.entries(i)){let s=r[a];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${a}`);if(o===null||typeof o!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${a} must be ${s.type}`)}return{...i}}async function eA(e,t,n,i){let r=QR(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:r,trigger:i,pm_root:n,...pd(n)}));a.catch(()=>{});let o;try{let s=await Promise.race([a,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??XR),o.unref?.()})]);return ZR(e,t.key,s)}finally{clearTimeout(o)}}function H_(e,t,n,i){let r=e;for(let a of t.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))throw new Ye(`assurance field ${t} is not present`,{source_kind:n,field:t,...i?{check:i}:{}});r=r[a]}if(typeof r=="number"&&Number.isFinite(r)||Array.isArray(r)&&r.every(a=>typeof a=="string"))return r;throw new Ye(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...i?{check:i}:{}})}function U_(e,t,n,i){let r=e.checks.find(a=>a.name===t);if(!r)throw new Ye(`assurance check ${t} is not present`,{source_kind:i,field:n,check:t});return{value:n==="status"||n==="ok"?r.ok?0:1:H_(r.details,n,i,t),population_size:1,cost:e.checks.length}}async function tA(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await KR("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function nA(e,t){let n=new Array(t.length),i=0,r=Array.from({length:Math.min(YR,t.length)},async()=>{for(;i<t.length;){let a=i;i+=1;let o=t[a],s=await Me(Ot(e,o.id),o.id);n[a]=s.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(r),n.flat()}async function Ti(e,t={}){let n=await T(e),i=H(n),r=fe(n.schema),a=(t.strict_read===!0?(await Dl(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await at(e,n.item_format,i.type_to_folder,void 0,n.schema)).map(m=>({...m,id:m.id,status:m.status,type:m.type})),o={path:e},s=F(),c=Object.fromEntries((s?.assurance_providers??[]).map(m=>[m.definition.id,{cost_class:m.runtime_definition.cost_class,network:m.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await tA(e,t.tree_id),items:a,history:t.include_history===!1?[]:await nA(e,a),terminal_statuses:[...r.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async m=>{if(m.kind==="graph"){let h=A({operation:m.operation,parameters:m.parameters??{}}),_=d.get(h);_===void 0&&(_=Ml(m.operation,void 0,void 0,{...m.parameters,full:!0},o),d.set(h,_));let w=await _;return{value:H_(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){l??=F_({counts:!0},o);let h=await l;return U_(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=yh(o,{checkOnly:!0,full:!0});let h=await u;return U_(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=$d(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return eA(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as iA}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 z_(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:i,limit:r}=Ki({...t,change:{}});return{policy:n,...i===void 0?{}:{cursor:i},...r===void 0?{}:{limit:r},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function rA(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 i=n;if(i.fingerprint!==t||typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return i.offset}function aA(e,t,n,i,r,a){let o=Object.fromEntries(Wa.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=iA("sha256").update(r);for(let f of i){let p=e.membership.get(f),h=n.has(f),_=p.family_ids.length>0;_&&h&&(s+=1),_||(c+=1),h||(d+=1);let w=t.get(f)?.escape_class;w!==void 0&&Wa.includes(w)&&(o[w]+=1,l+=1),m.update(A([f,h,t.get(f)??null,p.id,p.family_ids])),(!a||!_||!h)&&u.push(f)}return{classCounts:o,coveredCount:s,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function W_(e,t,n={}){Id(e);let i=n.limit??25;if(!Number.isSafeInteger(i)||i<1||i>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let r=new Set,a=new Map;for(let k of t){if(r.has(k.id))throw new TypeError(`Duplicate recurrence item ${k.id}`);r.add(k.id);let I=Vi(k);I!==void 0&&a.set(k.id,I)}let o=kd(e.families,a),s=[...o.membership.keys()].sort(),c=A({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:f,selected:p,fingerprint:h}=aA(o,a,r,s,c,n.uncoveredOnly===!0),_=rA(n.cursor,h);if(_>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(_,_+i).map(k=>{let I=o.membership.get(k),C=r.has(k);return{item_id:k,lineage_id:I.id,lineage_item_count:I.item_ids.length,family_ids:I.family_ids,present:C,...C?I.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=_+w.length,E=s.length===0?null:d.production_defect/s.length;return{ok:u===0&&m===0,fingerprint:h,items:w,total:p.length,has_more:v<p.length,...v<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:s.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:f,unclassified_item_count:s.length-f,class_counts:d,escape_rate:f===s.length?E:null,escape_rate_lower_bound:E},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:i},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as oA}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 lc,q_=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],uc=["measurement","assertion","gate"];function sA(e){if(q_.includes(e))return e;throw Zi({command_path:"assurance",token:e,allowed:q_,display_name:"assurance action"})}function Pn(e,t,n){throw new g(t,y.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function cA(e){if(!e)return Pn("kind",`Assurance declaration kind is required. Expected: ${uc.join(", ")}`,"pm assurance list measurement");if(uc.includes(e))return e;throw new g(`Assurance declaration kind is required. Expected: ${uc.join(", ")}`,y.USAGE)}function G_(e){if(!e)return Pn("preset",`Assurance preset is required. Expected: ${ni.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(ni.includes(e))return e;throw new g(`Assurance preset is required. Expected: ${ni.join(", ")}`,y.USAGE)}function mc(e){return e.owner?.trim()?e.owner.trim():Pn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function dA(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(i){throw new g("assurance definition must be valid JSON",y.USAGE,{reason:i instanceof Error?i.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new g("assurance put requires a JSON object definition",y.USAGE);return n}async function lA(e){let[t,n,i]=await Promise.all([Xn(e,"measurement"),Xn(e,"assertion"),Xn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:i.items}}function B_(e,t){return t===!0?{id:e.id}:e}async function uA(e,t){let n=t.authorization_decision;if(!n)return[];let i=await Ti(e,{include_history:!1,resolve_tree:!1}),r=i.items.find(o=>o.id===n),a=new Set(i.terminal_statuses);if(!r||r.type.toLowerCase()!=="decision"||!a.has(r.status))throw new g(`Assurance authorization ${n} must name a terminal Decision item`,y.USAGE);return[r.id]}async function mA(e,t){let n=Za(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>pn))throw new g(`assurance verdict limit must be an integer from 1 through ${pn}`,y.USAGE);let i=await tu(t,{gate_id:e.id??e.gate,limit:n});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function J_(e,t,n){try{return await to(()=>Zl(e,t,n))}catch(i){if(!(i instanceof g)||i.context.reason!=="assurance_evaluation_refused")throw i;let r=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],a=le(r);throw Object.assign(i.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:[a],recovery:{next_best_command:a,suggested_retry:a,suggested_retry_args:r}}),i}}async function pA(e,t,n){if(e==="presets"){if(t.preset??t.id)return Ar(G_(t.preset??t.id),mc(t));let r=ni.map(a=>{let o=Ar(a,"pm-owner");return{id:a,title:o.title,description:o.description}});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return mn(()=>Tu(n,G_(t.preset??t.id),mc(t),{author:t.author,message:t.message}));if(e==="derive"){let r=await $u(await Ti(n,{resolve_tree:!1,trigger:"derive"}),mc(t)),a=t.apply?await mn(()=>Du(n,r,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:r,count:r.length,...a?{applied:a}:{}}}if(!t.id)return Pn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new g("assurance promote requires --enforcement warn|block",y.USAGE);let i=await J_(n,"assertion",t.id);return mn(()=>Ou(n,i,t.enforcement,{author:t.author,message:t.message}))}async function fA(e,t,n){if(!e.id)return Pn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let i=e.id;if(!e.trigger)throw new g("assurance run requires a trigger",y.USAGE);if(!jt.includes(e.trigger))throw new g(`Unknown assurance trigger ${e.trigger}. Expected: ${jt.join(", ")}`,y.USAGE);let r=e.trigger,[a,o]=await Promise.all([lA(t),Ti(t,{...n.workspace,tree_id:e.tree,trigger:r})]),s=await to(()=>Yl(i,a,o,{trigger:r,dry_run:e.dry_run===!0}));return s.dry_run||await eu(t,s,{author:e.author,message:e.message}),s}function V_(e){throw e instanceof g?e:new g(e instanceof Error?e.message:"assurance risk request is invalid",y.USAGE)}function hA(e){if(e.limit!==void 0)throw new g(`assurance ${e.action} does not accept --limit; set limit inside the definition`,y.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new g(`assurance ${e.action} definition must be valid JSON`,y.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?z_(t):Ki(t)}catch(n){if(e.action==="risk"&&n instanceof xd)throw new g(n.message,y.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 V_(n)}}function _A(e,t){let n=new Set;for(let[i,r]of t)e.item_fingerprints.get(i)!==r&&n.add(i);for(let i of e.item_fingerprints.keys())t.has(i)||n.add(i);return n}function gA(e,t,n){let i=A(t.policy),r=lc?.pm_root===e?lc:void 0,a=new Map(n.map(d=>[d.id,oA("sha256").update(A([bd(d),Vi(d)])).digest("hex")])),o=r?.policy_serialized===i?r:void 0,s=o?_A(o,a):new Set,c=Ed(t.policy,o?n.filter(d=>s.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return lc={pm_root:e,policy_serialized:i,item_fingerprints:a,index:c},c}async function yA(e,t){let n=hA(e),i=await Ti(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Sd(gA(t,n,i.items),n.change,{cursor:n.cursor,limit:n.limit}):W_(n.policy,i.items,n)}catch(r){return V_(r)}}async function wA(e,t={},n={}){let i=sA(e.action),r=M(process.cwd(),t.path);if(i==="presets"||i==="apply"||i==="derive"||i==="promote")return pA(i,e,r);if(i==="verdicts")return mA(e,r);if(i==="run")return fA(e,r,n);if(["risk","lineages"].includes(i))return yA(e,r);let a=cA(e.kind);if(i==="list")return Xn(r,a);if(!e.id)return Pn("id",`assurance ${i} requires an id`,`pm assurance ${i} ${a} <id>`);let o=e.id;if(i==="show")return J_(r,a,o);if(i==="remove"){let l=await mn(()=>Ql(r,a,o,{author:e.author,message:e.message}));return B_(l,e.idOnly)}let s=dA(a,e.definition);if(s.id!==o)throw new g(`Assurance definition id ${s.id} does not match requested id ${o}`,y.USAGE);let c={author:e.author,message:e.message,...a==="assertion"?{authorized_decision_ids:await uA(r,s)}:{}},d=await mn(()=>kr(r,a,s,c));return B_(d,e.idOnly)}function uz(e,t,n){let i={...e,...t};return wA({action:Q(i,"subcommand")??Q(i,"assuranceAction")??Q(i,"operation")??"",kind:Q(i,"kind"),id:Q(i,"id"),definition:i.definition,trigger:Q(i,"trigger"),tree:Q(i,"treeId")??Q(i,"tree"),gate:Q(i,"gate"),limit:Za(i.limit,"assurance verdict limit"),dry_run:i.dryRun===!0||i.dry_run===!0,fullChangedFields:i.fullChangedFields===!0,idOnly:i.idOnly===!0,author:Q(i,"author"),message:Q(i,"message"),preset:Q(i,"preset"),owner:Q(i,"owner"),apply:i.apply===!0,enforcement:Q(i,"enforcement")},n)}import Ln from"node:fs/promises";import Ia from"node:path";import xa from"node:fs/promises";import pc 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 vA=864e5;function bA(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 kA(e,t){let n;try{n=await xa.readdir(e,{withFileTypes:!0})}catch(r){if(j(r))return[];throw r}let i=[];for(let r of n)if(r.isDirectory()){let a=pc.join(e,r.name),o;try{o=await xa.readdir(a)}catch(s){j(s)||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let s of o)s.endsWith(".json")&&i.push(`${r.name}/${s}`)}else r.name.endsWith(".json")&&i.push(r.name);return i.sort()}async function K_(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),a=Math.max(0,t.retentionDays)*vA,o=pc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await kA(o,s.warnings);for(let d of c){let l=pc.join(o,d),u=`checkpoints/${d}`;s.scanned+=1,i?.onRead&&s.warnings.push(...await i.onRead(l));let m;try{m=await xa.readFile(l,"utf8")}catch(w){if(j(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=bA(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${d}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=r-p,_={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>a,reason:h>a?"expired":"active"};if(!_.stale){s.retained.push(u),s.entries.push(_);continue}if(!n){try{await xa.unlink(l)}catch(w){if(!j(w)){s.warnings.push(`checkpoint_remove_failed:${d}`),s.retained.push(u),s.entries.push(_);continue}}i?.onWrite&&s.warnings.push(...await i.onWrite(l))}s.removed.push(u),s.entries.push(_)}return s}import fc from"node:fs/promises";import Y_ 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 EA=1440*60*1e3,SA=new Set(["committed","compensated"]);function xA(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 IA(e,t,n,i,r){let a=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(a))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=i-a;return SA.has(t)?o>r?{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 RA(e,t,n,i){let r=i.hooks?.onRead?await i.hooks.onRead(e):[],a=xA(await fc.readFile(e,"utf8")),o=IA(t,a.status,a.updatedAt,i.nowMs,i.retentionMs);return o.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),o.remove&&!i.dryRun&&(await fc.rm(e,{force:!0}),i.hooks?.onWrite&&r.push(...await i.hooks.onWrite(e))),{decision:o,warnings:r}}async function X_(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),a=Math.max(0,t.retentionDays)*EA,o=Y_.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await fc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(j(d))return s;throw d}for(let d of c){let l=Y_.join(o,d),u=`transactions/sdk/${d}`,m=await RA(l,u,d,{dryRun:n,hooks:i,nowMs:r,retentionMs:a});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.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]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var $i=["index","embeddings","runtime","locks","checkpoints","transactions"],AA=1440*60*1e3,CA=[{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 TA(e,t,n){let i=t.relativePath,r=Ia.join(e,i),a=await Ne({path:r,scope:"project"});try{let o=await Ln.stat(r);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...a,`not_a_file:${i}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...a,`not_a_directory:${i}`]};if(n)return{removed:!0,warnings:a};t.kind==="file"?await Ln.unlink(r):await Ln.rm(r,{recursive:!0,force:!0});let s=await K({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...a,...s]}}catch(o){if(j(o))return{removed:!1,warnings:a};throw o}}async function $A(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],i=[],r=[],a=[],o=Date.now()-AA;for(let s of n){let c=Ia.join(e,s.relativePath);if(!await D(c))continue;let d=(await Ln.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=Ia.posix.join(s.relativePath,l),m=Ia.join(c,l);a.push(...await Ne({path:m,scope:"project"}));let f=await Ln.stat(m).catch(p=>{if(!j(p))throw p});if(f){if(f.mtimeMs>o){r.push(u);continue}i.push(u),!t&&(await Ln.rm(m,{recursive:!0,force:!0}),a.push(...await K({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:i,retained:r,warnings:a}}function DA(e){if(!e||e.length===0)return[...$i];let t=e.flatMap(i=>i.split(",")).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);if(t.length===0)throw new g(`--scope requires at least one value (${$i.join(",")})`,y.USAGE);let n=new Set;for(let i of t){if(!$i.includes(i))throw new g(`Invalid --scope value "${i}". Expected one or more of: ${$i.join(", ")}`,y.USAGE);n.add(i)}return $i.filter(i=>n.has(i))}function OA(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"),i=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&i&&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(r=>r.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(r=>r.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 Pz(e,t={}){let n=M(process.cwd(),e.path);await ne(n);let i=await T(n),r=t.dryRun===!0,a=DA(t.scope),o=CA.filter(p=>a.includes(p.scope)),s=[],c=[],d=[];for(let p of o){let h=await TA(n,p,r);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(a.includes("runtime")){let p=await $A(n,r);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(a.includes("locks")){let p=await gm(n,{dryRun:r,hooks:{onRead:h=>Ne({path:h,scope:"project"}),onWrite:h=>K({path:h,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(a.includes("transactions")){let p=i.checkpoints.retention_days,h=await X_(n,{dryRun:r,retentionDays:p,hooks:{onRead:_=>Ne({path:_,scope:"project"}),onWrite:_=>K({path:_,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}let m;if(a.includes("checkpoints")){let p=i.checkpoints.retention_days,h=await K_(n,{dryRun:r,retentionDays:p,hooks:{onRead:_=>Ne({path:_,scope:"project"}),onWrite:_=>K({path:_,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}d.push(...await Ji({mode:r?"gc:dry-run":"gc",total_items:o.length}));let f=OA({dryRun:r,scopes:a,removed:s});return{ok:d.length===0,dry_run:r,scope:a,removed:s,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:$()}}import{execFile as PA}from"node:child_process";import LA from"node:path";import{promisify as NA}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]="7fe99df0-8454-5667-9205-0b861ba212d1")}catch{}})();var MA=NA(PA),Q_="@unbrained/pm-cli",jA="latest",FA={global:["--global"],project:[]};function Z_(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new g('Options "--project/--local" and "--global" are mutually exclusive.',y.USAGE);return n?"global":"project"}function Aa(e){return e.trim().toLowerCase()}function eg(e,t){let n=Aa(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(i=>typeof i=="string"&&Aa(i)===n)}function UA(e,t){let n=M(process.cwd(),t.path),i=Jt(n,process.cwd());return{selected_root:e==="global"?i.global:i.project}}async function HA(e,t,n){try{let i=await MA(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:i.stdout,stderr:i.stderr}}catch(i){let r=typeof i=="object"&&i!==null&&"stderr"in i?String(i.stderr??""):"",a=r.trim().length>0?r.trim():i instanceof Error?i.message:String(i);throw new g(`Command failed: ${e} ${t.join(" ")}
|
|
58
|
+
${a}`,y.GENERIC_FAILURE)}}function Ca(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():jA}function Ra(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Q_}async function zA(e,t){let n=e.commandRunner??HA,i=Ra(e),r=Ca(e),a=`${i}@${r}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=Oc(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:i,target:a,command:o,before_version:s,...i===Q_?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(o[0],o.slice(1));let d=await n("pm",["--version"]);return{...c,status:"updated",after_version:d.stdout.trim()||void 0}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function WA(e){return LA.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function qA(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!WA(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function GA(e,t){let n=qA(e,t);return e.kind!=="local"||await D(n)?n:await D(e.location)?e.location:n}function BA(e,t,n,i){let r=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&i&&i.trim().length>0&&r.push("--ref",i.trim()),r}async function tg(e,t){let n=UA(e,t);return(await he(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function JA(e,t,n){let i=await tg(e,t);return i.find(r=>eg(r,n.name))??i.find(r=>Aa(r.directory)===Aa(n.directory))}async function VA(e,t,n,i,r){let a=Ca(t),o=await GA(e.source,a),s=BA(e.source,o,i,e.source.ref),c={name:e.name,directory:e.directory,scope:i,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(r)return c;try{await ls(o,{install:!0,project:i==="project",global:i==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await JA(i,n,e);return{...c,status:"updated",installed_version:d?.manifest_version}}catch(d){return{...c,status:"failed",error:d instanceof Error?d.message:String(d)}}}function KA(e,t,n,i){let r=[n?e.status:void 0,...t.map(a=>a.status)].filter(a=>typeof a=="string");return{requested_cli:n,requested_packages:i,planned:r.filter(a=>a==="planned").length,updated:r.filter(a=>a==="updated").length,skipped:r.filter(a=>a==="skipped").length,failed:r.filter(a=>a==="failed").length}}async function zz(e,t,n){let i=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...i?[i]:[],"--packages-only","--dry-run",...FA[Z_(t)]];throw new g('Options "--cli-only" and "--packages-only" are mutually exclusive.',y.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:le(m),suggested_retry_args:m}})}let r=Z_(t),a=t.dryRun===!0;if(t.cliOnly===!0&&i)throw new g('A package target cannot be used with "--cli-only".',y.USAGE);let o=!(t.packagesOnly===!0||i),s=t.cliOnly!==!0,c=o?await zA(t,a):{requested:!1,status:"skipped",package:Ra(t),target:`${Ra(t)}@${Ca(t)}`,command:["npm","install","-g",`${Ra(t)}@${Ca(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await tg(r,n):[];if(i&&(d=d.filter(m=>eg(m,i)),d.length===0))throw new g(`Managed package "${i}" was not found in ${r} scope.`,y.NOT_FOUND);let l=[];for(let m of d)l.push(await VA(m,t,n,r,a));let u=KA(c,l,o,s);return{ok:u.failed===0,action:"upgrade",dry_run:a,scope:r,target:i,cli:c,packages:l,summary:u}}import{createHash as YA}from"node:crypto";import{isUtf8 as XA}from"node:buffer";import Di from"node:fs/promises";import hc 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]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function ng(e){try{return(await Di.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(j(t))return[];throw t}}function ZA(e,t,n,i){let r=t.at(-1),a;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){a=t[c];break}let o=t[0]?.context?.history_compaction,s=typeof o=="object"&&o!==null&&"pruned_stream_digest"in o&&typeof o.pruned_stream_digest=="string"?o.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:n,stream_digest:i,latest_after_hash:r?.after_hash??null,latest_record_hash:r?.record_hash??null,latest_hash_algorithm:r?Re(r.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:s,last_maintenance:a?{op:a.op,ts:a.ts,record_hash:a.record_hash??null}:null}}function QA(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!XA(t))return null;let i=[];for(let r of t.toString("utf8").split(/\r?\n/u)){if(!r.trim())continue;let a=JSON.parse(r);if(typeof a!="object"||a===null||Array.isArray(a))return null;let o=a;if(![o.op,o.author,o.ts,o.before_hash,o.after_hash].every(s=>typeof s=="string")||!Array.isArray(o.patch))return null;i.push(o)}return Gn(i).ok?ZA(e,i,t.length,n):null}catch{return null}}async function _c(e,t){if(!(await Di.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=hc.join(e,"history"),i=await ng(n),r=new Map,a=[];for(let o of i){let s=o.slice(0,-6),c={id:s,digest:null,stream:null};a.push(c);let d=hc.join(n,o);try{let l=await Di.lstat(d);if(r.set(o,A([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await Di.readFile(d);c.digest=YA(t).update(u).digest("hex"),c.stream=QA(s,u,c.digest)}catch{}}if(A(i)!==A(await ng(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of r){let c=await Di.lstat(hc.join(n,o));if(s!==A([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}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]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Nn(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function eC(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:Nn(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||Nn(e.latest_record_hash,e.latest_hash_algorithm))}function tC(e){return e===null?!0:!gc(e)||!yc(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&vt(e.ts)&&(e.record_hash===null||Nn(e.record_hash,"sha256")||Nn(e.record_hash,"sha512"))}function nC(e,t){return!gc(e)||!yc(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&Nn(e.stream_digest,t)&&eC(e)&&(e.checkpoint_digest===null||Nn(e.checkpoint_digest,"sha256"))&&tC(e.last_maintenance)}function ig(e){if(!gc(e)||!yc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==qa.format||e.version!==1||typeof e.generated_at!="string"||!vt(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,n;for(let a of e.streams){if(!nC(a,t))throw new TypeError("Invalid history attestation stream");let o=a.id;if(n!==void 0&&o<=n)throw new TypeError("Invalid history attestation stream order");n=o}let{workspace_digest:i,...r}=e;if(Ga(A(r),t)!==i)throw new TypeError("History attestation rollup mismatch");return e}async function rg(e={}){let t=Re(e.hashAlgorithm),n=e.generatedAt??$();if(!vt(n))throw new TypeError("Invalid history attestation timestamp");let i=await _c(M(e.cwd??process.cwd(),e.pmRoot),t),r=i.filter(o=>o.stream===null);if(r.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${r.map(o=>o.id).join(", ")}`);let a={format:qa.format,version:1,hash_algorithm:t,generated_at:n,streams:i.map(o=>o.stream)};return ig({...a,workspace_digest:Ga(A(a),t)})}async function ag(e,t={}){let n=ig(e),i=await _c(M(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),r=new Map(i.map(l=>[l.id,l])),a=new Map(n.streams.map(l=>[l.id,l])),o=n.streams.filter(l=>!r.has(l.id)).map(l=>l.id),s=i.filter(l=>!a.has(l.id)).map(l=>l.id),c=i.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of n.streams){let u=r.get(l.id);u&&(u.digest!==l.stream_digest||A(u.stream)!==A(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:o.length+s.length+c.length+d.length===0,workspace_digest:n.workspace_digest,streams_checked:i.length,changed_streams:d.map(l=>l.id),missing_streams:o,added_streams:s,invalid_streams:c,transitions:d}}import og 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]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function mW(e,t){for(let i of["verify","output","hashAlgorithm"]){let r=e[i];if(!(i==="verify"&&typeof r=="object"&&r!==null)&&r!==void 0&&(typeof r!="string"||r.trim().length===0))throw new g(`history attest ${i} requires a nonempty string.`,y.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new g("history attest --verify cannot be combined with --output or --hash-algorithm",y.USAGE);let i;try{i=typeof e.verify=="string"?JSON.parse(await og.readFile(e.verify,"utf8")):e.verify}catch{throw new g("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",y.USAGE)}return ag(i,{pmRoot:t.path})}let n=await rg({pmRoot:t.path,hashAlgorithm:Re(e.hashAlgorithm)});if(e.output===void 0)return n;try{await og.writeFile(e.output,`${JSON.stringify(n,null,2)}
|
|
59
|
+
`,{flag:"wx",mode:384})}catch{throw new g("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",y.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.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]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function sg(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 cg(e,t,n=process.platform){let i=["--pm-path",t];return e==="merge_evidence_invalid"?le([...i,"merge","report"],n):e==="history_evidence_invalid"?le([...i,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?le([...i,"merge","reconcile"],n):e==="history_repair_required"?le([...i,"history-repair","--all"],n):e==="merge_fence_unprepared"?le([...i,"merge","install"],n):null}function dg(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 xW(e){let t=M(process.cwd(),e.path);await ne(t);let n=await T(t),i=H(n,F()),r=[],a=await ga({includeBody:!0,pmRoot:t,settings:n,typeToFolder:i.type_to_folder,warnings:r}),o=await St(t),[s,c,d,l]=await Promise.all([ln(t,dn(n)),o===null?Promise.resolve(null):un(o),ft(o??t,{includeLossless:!0,pmRoot:t}),ya(t,a,!1)]),{pendingDecisions:u,lossless:m}=Cn(d.receipts),f=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),p=l.check.details,h=dg(p),_=sg({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:s,drivers:c});return{ok:_==="ready",state:_,merge_fence:{committed:s,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:f.slice(0,25),pending_item_ids_truncated:f.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:cg(_,t),reason:_},warnings:[...new Set(r)].sort((w,v)=>w.localeCompare(v)),generated_at:$()}}function IW(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(`
|
|
60
|
+
`)}var RW={commandForWorkspacePositionState:cg,normalizeWorkspaceHistoryDrift:dg,selectWorkspacePositionState:sg};import iC from"node:fs/promises";import Oi 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]="f02db25d-bedb-5411-b50a-de0fea51a117")}catch{}})();var wc="index/manifest.json",vc="search/embeddings.jsonl",rC="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function aC(e){return e.progress===!0||process.stderr.isTTY===!0}function oe(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
|
|
61
|
+
`)}catch{}}function oC(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new g("Reindex mode must be one of keyword|semantic|hybrid",y.USAGE)}async function sC(e,t,n,i){let r=[];return{candidates:await ll(e,t,n,r,i),warnings:r}}async function kc(e,t,n,i,r){let a=Gt(F()),o=[];for(let s of t)if(!(r&&!r.has(s.metadata.id))){if(typeof s.body=="string"){o.push({metadata:s.metadata,body:s.body});continue}try{let c=await iC.readFile(s.item_path,"utf8"),d=bt(c,{format:s.item_format,schema:n,extensionFieldNames:a,onWarning:l=>i.push(l)});o.push({metadata:s.metadata,body:d.body})}catch{i.push(`item_list_item_read_failed:${Oi.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function cC(e,t,n){let i=e.metadata;return{id:i.id,mode:t,updated_at:i.updated_at,corpus:pl(e,{fields:n})}}var Mn=Y;function dC(e){let t=F(),n=Mn(e.search?.provider);if(!n)return null;let i=Dd(t,n);if(!i)return null;let r=i.runtime_definition??i.definition,a=Mn(r.name)??Mn(i.definition.name);if(!a)return null;let o=r.embedBatch,s=r.embed_batch,c=r.embed,d=typeof o=="function"?o:typeof s=="function"?s:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:a,embedBatch:d,embed:l}}function lC(e){let t=F(),n=Mn(e.vector_store?.adapter);if(!n)return null;let i=Od(t,n);if(!i)return null;let r=i.runtime_definition??i.definition,a=Mn(r.name)??Mn(i.definition.name);if(!a)return null;let o=r.upsert,s=r.delete;return{adapterName:a,...typeof o=="function"?{upsert:o}:{},...typeof s=="function"?{delete:s}:{}}}function bc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new g(`Invalid vector returned by ${t}`,y.GENERIC_FAILURE);return e}async function uC(e,t,n){let i=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let a=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:i}));if(!Array.isArray(a))throw new g(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,y.GENERIC_FAILURE);return a.map((o,s)=>bc(o,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new g(`Extension search provider "${e.name}" does not implement embed/embedBatch`,y.GENERIC_FAILURE);let r=[];for(let[a,o]of n.entries()){let s=await Promise.resolve(e.embed({input:o,settings:t,model:i}));r.push(bc(s,`extension search provider "${e.name}" embed output at index ${a}`))}return r}function lg(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function ug(e,t,n){let i=n?Mt(n.name,lg(e)):t?Mt(t.name,t.model):null;if(!i)throw new g("No embedding identity available for semantic reindex mode",y.USAGE);return i}function mC(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,i)=>n.localeCompare(i))}async function mg(e,t,n,i,r,a,o,s){let c=i?.name??n?.name,d=fl(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Ka(e),u=r.map(p=>hl(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(i)try{m=await uC(i,e,u),f=Mt(i.name,lg(e))}catch(p){if(!n)throw new g(`Extension search provider "${i.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,y.GENERIC_FAILURE);a.push(`Extension search provider "${i.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new g(`No embedding executor available for reindex mode '${t}'`,y.USAGE);let p=await _l(n,e,u,{onProgress:h=>{h.phase==="complete"&&(o.batches_completed=h.batch_index),oe(s,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});a.push(...p.warnings),o.batching=p.receipt,m=p.vectors,f=Mt(n.name,n.model)}if(oe(s,`embedding_complete vectors=${m.length}`),m.length!==r.length)throw new g(`Embedding output size mismatch (expected ${r.length}, received ${m.length})`,y.GENERIC_FAILURE);if(!f)throw new g(`No embedding identity available for reindex mode '${t}'`,y.USAGE);return{vectors:m,embeddingIdentity:f}}async function pC(e,t,n,i,r,a){let o=Object.keys(n);if(t){if(o.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:o.sort((s,c)=>s.localeCompare(c)),settings:i}))}catch(s){throw new g(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,y.GENERIC_FAILURE)}else o.length>0&&r.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${o.length}`);if(!e)return}e&&await wl(e,o,{},a)}async function pg(e,t,n,i,r){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:i}))}catch(a){throw new g(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${a instanceof Error?a.message:String(a)}`,y.GENERIC_FAILURE)}else r.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await yl(e,n)}}function fC(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function hC(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(i=>({id:i.metadata.id,type:i.metadata.type,status:i.metadata.status,priority:i.metadata.priority,updated_at:i.metadata.updated_at}))}}function _C(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Bn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new g(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,y.USAGE);let n=fr(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new g(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,y.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function gC(e){let t=H(e.settings,F()),n=await sC(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(i=>({metadata:i.metadata,body:typeof i.body=="string"?i.body:""}))}}async function yC(e){let t=await cn(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return ug(e.settings,Bn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&sn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(rC))}async function wC(e){let t=await cn(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=ug(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),i=new Set(e.metadataDocuments.map(d=>d.metadata.id)),r=mC(t.entries,i),a=sn(t.embedding,n);e.forceFullSemantic&&!a&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let o=e.forceFullSemantic||a?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),s=new Set(o.map(d=>d.metadata.id)),c=s.size>0?await kc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:r,resetRequired:a,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function vC(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await kc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,oe(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let i=await mg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...i,staleDocuments:n,vectorDimension:Ya(i.vectors,"Reindex embeddings")}}async function bC(e){let t=await mg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,i=t.embeddingIdentity,r=Ya(n,"Reindex embeddings");if(!(!e.resetRequired&&(sn(e.ledgerEmbedding,i)||bl(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:i,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let a=await vC(e);return n=a.vectors,i=a.embeddingIdentity,r=a.vectorDimension,{vectors:n,embeddingIdentity:i,staleDocuments:a.staleDocuments,vectorDimension:r,resetRequired:!0}}async function kC(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(oe(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new g(`Extension vector adapter "${t}" does not support upserting vectors.`,y.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,oe(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof g)throw t;if(!e.activeVectorStore)throw new g(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,y.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),oe(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){oe(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await gl(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,oe(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new g(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,y.USAGE)}function EC(e,t){return e.map((n,i)=>({id:n.metadata.id,vector:bc(t[i],`reindex embeddings output at index ${i}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function SC(e){oe(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await bC({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(oe(e.progressEnabled,"vector_reset_start"),await pC(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),oe(e.progressEnabled,"vector_reset_complete")):await pg(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=EC(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await kC({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:vl(t.embeddingIdentity,t.vectorDimension)}}async function xC(e){let t=await wC(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(a=>[a.metadata.id,a.metadata.updated_at]));if(oe(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return oe(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await pg(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let i=await SC({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let r=new Map(i.staleDocuments.map(a=>[a.metadata.id,a]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(a=>r.get(a.metadata.id)??a),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:i.embeddingMetadata}}async function IC(e){let t=Oi.join(e.pmRoot,wc),n=Oi.join(e.pmRoot,vc),i=Ka(e.settings),r=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(cC(o,e.mode,i))).join(`
|
|
62
62
|
`);oe(e.progressEnabled,"writing keyword artifacts"),await Z(t,`${JSON.stringify(e.manifest,null,2)}
|
|
63
63
|
`),await Z(n,`${r}
|
|
64
|
-
`);let a=[];if(e.mode!=="keyword")try{oe(e.progressEnabled,"writing vectorization status ledger"),await
|
|
65
|
-
//# sourceMappingURL=chunk-
|
|
64
|
+
`);let a=[];if(e.mode!=="keyword")try{oe(e.progressEnabled,"writing vectorization status ledger"),await kl(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(o){a.push(`search_vectorization_status_ledger_write_failed:${o instanceof Error?o.message:String(o)}`)}return a}async function OW(e,t){let n=oC(e.mode),i=aC(e),r=e.full===!0;oe(i,`start mode=${n}`);let a=M(process.cwd(),t.path);await ne(a);let o=ur(await T(a)).settings,s=null;try{s=await re(a,tl,o.locks.ttl_seconds,z(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof g&&c.exitCode===y.CONFLICT?new g("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",y.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=dC(o),d=lC(o),l=_C({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;oe(i,"loading item corpus");let m=await gC({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;oe(i,`loaded_items=${h.length}`);let _=$(),w=hC(u,_,h),v=Oi.join(a,wc),E=Oi.join(a,vc),k=u==="keyword"?await kc(a,p,o.schema,f):h,I=[],C={},S=null,b=fC(u);if(u==="keyword"&&await yC({pmRoot:a,settings:o,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let x=await xC({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:k,forceFullSemantic:r,reindexWarnings:f,semanticWarnings:I,semanticSummary:b,progressEnabled:i});k=x.documentsForKeywordArtifacts,C=x.vectorizationLedgerEntries,S=x.vectorizationEmbeddingMetadata}let O=await IC({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:C,vectorizationEmbeddingMetadata:S,progressEnabled:i}),P=[...await K({path:v,scope:"project",op:"reindex:manifest"}),...await K({path:E,scope:"project",op:"reindex:embeddings"}),...await Ji({mode:u,total_items:h.length})];return oe(i,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:wc,embeddings:vc},warnings:[...f,...I,...O,...P],generated_at:_}}finally{await s?.()}}export{L as a,we as b,Ye as c,mn as d,to as e,Ul as f,jt as g,no as h,Sg as i,ao as j,oo as k,ql as l,fn as m,Yn as n,co as o,Wg as p,Yl as q,Xn as r,Zl as s,kr as t,lo as u,Ql as v,eu as w,tu as x,go as y,uu as z,YC as A,iy as B,XC as C,ay as D,eT as E,hu as F,cy as G,vT as H,dv as I,BD as J,KD as K,YD as L,ci as M,XD as N,ZD as O,QD as P,eO as Q,tO as R,nO as S,iO as T,rO as U,aO as V,oO as W,sO as X,ns as Y,ls as Z,I$ as _,rm as $,my as aa,bu as ba,DT as ca,ti as da,OT as ea,wy as fa,vy as ga,PT as ha,by as ia,qh as ja,FT as ka,Au as la,Bh as ma,KF as na,YF as oa,ni as pa,Ar as qa,Tu as ra,$u as sa,Du as ta,Ou as ua,Mu as va,Fu as wa,Uu as xa,Wu as ya,At as za,rM as Aa,aM as Ba,oM as Ca,sM as Da,hM as Ea,Lf as Fa,ca as Ga,FM as Ha,ft as Ia,qf as Ja,UM as Ka,HM as La,t0 as Ma,a0 as Na,Kf as Oa,Hy as Pa,Gu as Qa,xs as Ra,P1 as Sa,L1 as Ta,Tr as Ua,$r as Va,yh as Wa,Lj as Xa,wh as Ya,bh as Za,kh as _a,xh as $a,Rh as ab,SI as bb,xI as cb,eU as db,tU as eb,nU as fb,iU as gb,RI as hb,AI as ib,CI as jb,rU as kb,Kh as lb,$I as mb,Yh as nb,Gs as ob,Zh as pb,DI as qb,OI as rb,PI as sb,Ks as tb,Ys as ub,hU as vb,_U as wb,gU as xb,uR as yb,AH as zb,F_ as Ab,Ti as Bb,z_ as Cb,W_ as Db,q_ as Eb,uc as Fb,wA as Gb,uz as Hb,Pz as Ib,zz as Jb,ig as Kb,rg as Lb,ag as Mb,mW as Nb,xW as Ob,IW as Pb,RW as Qb,OW as Rb};
|
|
65
|
+
//# sourceMappingURL=chunk-HPWT3RBG.js.map
|