@unbrained/pm-cli 2026.10.25 → 2026.10.26
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 +28 -0
- package/dist/cli/error-guidance.d.ts +5 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-O3ZTGRIH.js → chunk-25MTQAHX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TLMXSYJA.js → chunk-57YPOOED.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4GD6QOP6.js → chunk-7UDQAINZ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-LNKPH2DD.js → chunk-ER7RLJW5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YCCGZHOR.js → chunk-MWCG25PO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-444VPGQT.js → chunk-N6FTEILW.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-FNZT4BTE.js → chunk-NGKTROAO.js} +86 -86
- package/dist/cli-bundle/chunks/chunk-OCDRHIVQ.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-3CYXE6BV.js → chunk-ONC4BBQP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RQKDANP7.js → chunk-OUDR2HWR.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-RD6UW3MW.js → chunk-T7T4WLUY.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-MVJGGCGQ.js → chunk-TGOG5BFM.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-UF6EXZSP.js +2 -0
- package/dist/cli-bundle/chunks/chunk-VS2IIV3F.js +128 -0
- package/dist/cli-bundle/chunks/chunk-XAIR53QZ.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-VAEB6IUQ.js → chunk-Y42DYMZX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-EYCVAAIP.js → chunk-YJBIPNDL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UI3FD3DW.js → chunk-Z35XAHUN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7C3GCLOO.js → chunk-ZLVFUZI4.js} +27 -27
- package/dist/cli-bundle/chunks/{chunk-7T3H24HN.js → chunk-ZT64RDMF.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-47I6KKDO.js → indexed-receipt-blobs-NWQIDTH7.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-747C6IUR.js → mutation-admission-VTNV6JV2.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-COST6KRV.js → register-list-query-LZDWUZS4.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-M2A7PH42.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-S4LKLUBJ.js → register-operations-E7P2JTXM.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-3ITZXPOL.js → register-setup-DOV7KGSH.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-5IVCF6ZY.js → settlement-hook-SVD6CO7U.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-3UUIYROS.js → stage-LYLEOAQB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HMYDUEQK.js → chunk-226XKW3W.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-ABMNYWV6.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3M5FZCMC.js → chunk-ADSBGYLW.js} +8 -8
- package/dist/cli-bundle/focused-chunks/{chunk-22727JYL.js → chunk-B266DDBJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Y4JHHY24.js → chunk-BH7RE2ZY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-BL77VCRB.js +22 -0
- package/dist/cli-bundle/focused-chunks/{chunk-77NU7NPN.js → chunk-CSCZYSNZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-URWYYJ7K.js → chunk-D5YQ4KAE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZYCOMRFT.js → chunk-E5C24MCV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-74KC7FUQ.js → chunk-I7H3XF25.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IF6C43IP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-KERJNFXY.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-46KDJH3K.js → chunk-KTXU5WU6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NE27VCU7.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NI5SG2M2.js → chunk-NFN2P4TW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NC5HUGHU.js → chunk-NLZUI234.js} +4 -4
- package/dist/cli-bundle/focused-chunks/chunk-PK5FJIVA.js +12 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LWJ2X75I.js → chunk-UHWTPOM4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-B5JOVH5F.js → chunk-UP765R2V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-U6HXIF6G.js → chunk-WDWHUJQW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7DEZT4JN.js → chunk-YQKLKRMW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-YTEC2EPM.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3FM75SBJ.js → chunk-YW5GHQN2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-YCLN2ZZG.js → indexed-receipt-blobs-YFDNGHCM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-BQBQXILV.js → mutation-admission-L42E3U5U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-XVS6P2XI.js → settlement-hook-3CADO4XZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-VSIL4MTZ.js → stage-TUQHWU7N.js} +2 -2
- package/dist/cli-bundle/main.js +4 -4
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +23 -23
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +9 -9
- package/dist/core/extensions/extension-types.d.ts +3 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/policy/workflow-policy-store.js +1 -1
- package/dist/core/shared/errors.d.ts +9 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/secret-rules.d.ts +17 -0
- package/dist/core/shared/secret-rules.js +2 -1
- package/dist/core/store/item-mutation-precondition.d.ts +8 -0
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- 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/registration-helpers.d.ts +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +4 -0
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/context-signal-store.js +2 -2
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/index.d.ts +2 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/close-many.d.ts +3 -0
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.d.ts +3 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.d.ts +2 -0
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/plan.d.ts +2 -0
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle-policy.d.ts +11 -0
- package/dist/sdk/lifecycle-policy.js +1 -1
- package/dist/sdk/mutation-guard.d.ts +6 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/output/fit-envelope.d.ts +98 -0
- package/dist/sdk/output/fit-envelope.js +2 -0
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query.d.ts +1 -0
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output-session.d.ts +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +2 -2
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/scheduling-shortcuts.d.ts +2 -0
- package/dist/sdk/scheduling-shortcuts.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +3 -1
- package/dist/sdk/workspace-transaction.js +2 -2
- package/docs/COMMANDS.md +2 -1
- package/docs/MUTATION_INTEGRITY.md +33 -0
- package/docs/QUALITY_EVIDENCE.md +9 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +55 -1
- package/docs/SDK.md +88 -6
- package/docs/WORKFLOW_POLICIES.md +14 -1
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/agent-task-transcripts.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -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/shortcuts.ts +2 -2
- 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-5ZPT67NJ.js +0 -127
- package/dist/cli-bundle/chunks/chunk-HMJSFWHK.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RLXK2S7P.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XYLBOXSH.js +0 -6
- package/dist/cli-bundle/chunks/register-mutation-JZVVJUHY.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-5LBZR6YW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IVLIUPVV.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-KIIGME23.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MT5TYMEU.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-QH5KMIYZ.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-W7MCCFYV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WMPDY5ZU.js +0 -21
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as Et,d as on,e as sn,f as cn,g as Cl,j as Tl}from"./chunk-HMYDUEQK.js";import{a as Al}from"./chunk-Y4JHHY24.js";import{d as Q,h as Va,s as kl}from"./chunk-KIIGME23.js";import{a as Pa,c as ji,d as Fi,e as Jc,g as Vc,h as Na,i as Kc,j as Vt,k as Kt,l as Yc,m as Xc,n as Ma,o as ed,p as Yt,q as Xt,r as td,s as nd,t as ja}from"./chunk-7DEZT4JN.js";import{a as Ua}from"./chunk-SVOOGGAK.js";import{B as fd,C as qi,D as hd,E as Fa,G as _d,H as gd,J as yd,K as wd,L as Gi,U as Bi}from"./chunk-MT5TYMEU.js";import{K as $l}from"./chunk-74KC7FUQ.js";import{A as Rl,I as Ya,w as xl,y as Ka,z as Il}from"./chunk-77NU7NPN.js";import{$ as dr,Aa as Ja,C as Ed,G as Sd,H as xd,I as Id,L as ar,Na as yl,Oa as wl,Sa as vl,Ta as bl,aa as Vd,ba as qa,ca as zn,ea as Ga,i as Ji,ia as ol,ja as sl,ka as cl,la as dl,m as Mn,ma as mr,n as vd,o as bd,oa as ll,p as jn,pa as ul,qa as ml,ra as Nt,sa as pl,ta as rn,ua as fl,va as Ba,wa as an,x as kd,xa as hl,ya as _l,za as gl}from"./chunk-WMPDY5ZU.js";import{a as Wc,b as Jt,c as La,d as qc,e as Gc,f as tt,g as Ui,h as Bc,i as yt}from"./chunk-ZYCOMRFT.js";import{m as Wn,o as pr,v as El,y as Sl}from"./chunk-URWYYJ7K.js";import{A as lr,C as il,D as ge,E as ye,F as rl,G as ur,H as it,I as rt,M as al,N as at,a as Vi,c as Wd,j as Kd,k as Yd,m as Xd,n as Zd,o as kt,p as Qd,q as el,u as tl,v as nl}from"./chunk-QH5KMIYZ.js";import{$a as cr,Aa as Hd,Ca as nr,Da as ir,Ea as Un,Fa as bt,Ga as Hn,Ha as zd,Ia as rr,Ja as Lt,Ka as re,La as or,Ma as qd,Na as Wa,Oa as sr,Pa as tn,Qa as nn,Sa as Gd,Ta as Bd,Wa as Me,Za as Jd,_a as $,a as Rd,aa as z,ba as Pd,ca as nt,d as Re,da as Ld,db as te,e as Ha,f as Ad,ja as Nd,k as Ki,ka as za,l as Fn,la as Qi,m as Cd,ma as Qt,n as Yi,o as $d,oa as er,pa as Md,q as Xi,qa as jd,r as Zi,sa as Fd,t as Td,u as Te,ua as Ud,x as vt,xa as tr,y as Dd,z as Od,za as en}from"./chunk-LWJ2X75I.js";import{b as qt}from"./chunk-3FM75SBJ.js";import{a as oe,c as $e,e as Ie,f as Ve,j as fe,k as Zc,l as Hi,n as Qc}from"./chunk-22727JYL.js";import{Ad as Pt,Ba as $c,Bb as Fc,Ca as Dt,Cb as Uc,Cc as dd,Dc as de,Ea as Tc,Fa as A,Fd as ud,Ga as Dc,Ha as xe,Id as md,Ja as Mi,Jd as pd,Ka as Oc,Kb as Hc,Kd as ie,La as $a,Lb as Ot,Ma as Ta,Na as Da,Nb as Oa,O as Sc,Ob as zc,Pa as Pc,Pb as Bt,Qa as Lc,R as xc,Rb as Be,T as Ca,Ta as Nc,Tb as Je,Wb as id,Y as ue,Yb as zi,Z as qe,Zb as rd,_ as Ic,_b as ad,a as _c,aa as Y,ac as od,bb as Mc,d as gc,da as Rc,e as yc,ic as F,kb as jc,mc as K,o as Aa,oa as Ac,oc as Ne,pa as Cc,pc as sd,qa as H,qc as Wi,va as Nn,wa as M,wd as T,xa as Ge,xc as cd,xd as ld,ya as Ni,yd as Zt,za as Gt,zd as wt}from"./chunk-NC5HUGHU.js";import{a as qn}from"./chunk-VVRXF4JO.js";import{A as Ln,B as D,C as gt,D as j,E as B,H as Z,a as Oi,d as Pi,o as wc,q as vc,s as bc,u as kc,v as Li,w as Ec,y,z as g}from"./chunk-46KDJH3K.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 dn(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 Xa(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 sg}from"node:crypto";import cg 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 ln=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 Ol=1,Mt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Za=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],dg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],lg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,fr=30,hr=5e3,Pl=4,ug=50;function ot(e,t){if(!lg.test(e))throw new L(`${t} must be a stable lowercase id`)}function mg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Gn(e){let t=dg.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 eo(e,t){return A(e)===A(t)}function Ll(e,t){if(t.polarity==="equals")return eo(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 Nl(e){let t=Gn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Ll(i.observed,t)===(i.expected==="pass"))}function pg(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!eo(e.value,t.value)}function fg(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 pg(Gn(e),Gn(t))||n[t.enforcement]<n[e.enforcement]||i}function hg(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 _g(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 gg(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 to(e){ot(e.id,"measurement.id"),e.max_cost!==void 0&&mg(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 ${Za.join(", ")}`);let n=Reflect.get(t,"kind");if(!Za.includes(n))throw new L(`measurement.source.kind must be one of ${Za.join(", ")}`);let i=t;if(i.kind==="items"&&hg(i),i.kind==="dependency_kind"&&_g(i),i.kind==="prose_edge_gap"&&gg(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 no(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=Gn(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(!Nl(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function yg(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(!Mt.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 Ml(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 ${Mt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Mt.includes(t))throw new L(`gate trigger must be one of ${Mt.join(", ")}`);return e.provider_policy&&yg(e.provider_policy),e}function un(e){if(e.version!==Ol)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(to(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(no(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){Ml(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 jl(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function io(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)io(n,t)}function jl(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=[];io(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function wg(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"&&io(o.source.expression,n)}return r}function Bn(){return{version:Ol,measurements:[],assertions:[],gates:[]}}function vg(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 eo(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function bg(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 kg(e,t){let n=[],i=Ca(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=Ca(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&bg(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 Eg(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 Sg(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 Qa(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function xg(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(Qa(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(Qa(o.id,s));for(let s of Eg(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 Ig(e,t){let n=xg(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=Qa(o.holder_id,d);if(n.linked_pairs.has(l)||Sg(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 Rg(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 Ag(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 Cg(e,t){let n=e.source;return n.kind==="items"?vg(n,t):n.kind==="dependency_kind"?kg(n,t):n.kind==="prose_edge_gap"?Ig(n,t):n.kind==="history"?Rg(n,t):n.kind==="links"?Ag(n,t):null}function Fl(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 Ul(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 Hl(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 zl(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 Ul(e.operands,Pl,o=>Hl(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 Tg(e,t,n,i,r){to(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await Hl(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=Cg(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=Fl([...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:${sg("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 zl(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=Tg(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 ro(e,t,n=[e]){return zl(e,t,n,[],{cache:new Map,charged:new Set})}function Dg(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 Og(e,t,n={}){no(e);let i=Gn(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:Dg(t.value,i),verdict:r?"retired":Ll(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Nl(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Pg(e,t,n,i){let r=wg(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 Dl(e,t,n,i,r){try{return await ro(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 Wl(e,t,n,i){un(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}`);Pg(r,t,n,i.trigger);let a=await Ul(r.assertion_ids,Pl,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 Dl(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 Og(d,await Dl(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:Fl(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function _r(e){return cg.join(e,"assurance.json")}async function ql(e){let t=await B(_r(e));return t===null?Bn():gr(t)}function gr(e){try{return un(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 yr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Lg(e,t){e==="measurement"?to(t):e==="assertion"?no(t):Ml(t)}async function Jn(e,t){let n=structuredClone(yr(await ql(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Gl(e,t,n){let i=yr(await ql(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function wr(e,t,n,i={}){Lg(t,n);let r=await $(e),a=z(i.author,r.author_default),o=await tn({pmRoot:e,filePath:_r(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:fr,lockWaitMs:hr,mutate:s=>{let c=s===null?Bn():gr(s),d=yr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&fg(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),un(c),{raw:`${JSON.stringify(c,null,2)}
|
|
1
|
+
import{c as Et,d as on,e as sn,f as cn,g as Cl,j as Tl}from"./chunk-226XKW3W.js";import{a as Al}from"./chunk-BH7RE2ZY.js";import{d as Q,h as Va,s as kl}from"./chunk-IF6C43IP.js";import{a as Pa,c as ji,d as Fi,e as Jc,g as Vc,h as Na,i as Kc,j as Vt,k as Kt,l as Yc,m as Xc,n as Ma,o as ed,p as Yt,q as Xt,r as td,s as nd,t as ja}from"./chunk-YQKLKRMW.js";import{a as Ua}from"./chunk-SVOOGGAK.js";import{B as fd,C as qi,D as hd,E as Fa,G as _d,H as gd,J as yd,K as wd,L as Gi,U as Bi}from"./chunk-YTEC2EPM.js";import{K as $l}from"./chunk-I7H3XF25.js";import{A as Rl,I as Ya,w as xl,y as Ka,z as Il}from"./chunk-CSCZYSNZ.js";import{$ as dr,Aa as Ja,C as Ed,G as Sd,H as xd,I as Id,L as ar,Na as yl,Oa as wl,Sa as vl,Ta as bl,aa as Vd,ba as qa,ca as zn,ea as Ga,i as Ji,ia as ol,ja as sl,ka as cl,la as dl,m as Mn,ma as mr,n as vd,o as bd,oa as ll,p as jn,pa as ul,qa as ml,ra as Nt,sa as pl,ta as rn,ua as fl,va as Ba,wa as an,x as kd,xa as hl,ya as _l,za as gl}from"./chunk-BL77VCRB.js";import{a as Wc,b as Jt,c as La,d as qc,e as Gc,f as tt,g as Ui,h as Bc,i as yt}from"./chunk-E5C24MCV.js";import{m as Wn,o as pr,v as El,y as Sl}from"./chunk-D5YQ4KAE.js";import{B as lr,D as il,E as ge,F as ye,G as rl,H as ur,I as it,J as rt,N as al,O as at,a as Vi,c as Wd,j as Kd,k as Yd,m as Xd,n as Zd,o as kt,p as Qd,q as el,v as tl,w as nl}from"./chunk-NE27VCU7.js";import{$a as cr,Aa as Hd,Ca as nr,Da as ir,Ea as Un,Fa as bt,Ga as Hn,Ha as zd,Ia as rr,Ja as Lt,Ka as re,La as or,Ma as qd,Na as Wa,Oa as sr,Pa as tn,Qa as nn,Sa as Gd,Ta as Bd,Wa as Me,Za as Jd,_a as $,a as Rd,aa as z,ba as Pd,ca as nt,d as Re,da as Ld,db as te,e as Ha,f as Ad,ja as Nd,k as Ki,ka as za,l as Fn,la as Qi,m as Cd,ma as Qt,n as Yi,o as $d,oa as er,pa as Md,q as Xi,qa as jd,r as Zi,sa as Fd,t as Td,u as Te,ua as Ud,x as vt,xa as tr,y as Dd,z as Od,za as en}from"./chunk-UHWTPOM4.js";import{b as qt}from"./chunk-YW5GHQN2.js";import{a as oe,c as $e,e as Ie,f as Ve,j as fe,k as Zc,l as Hi,n as Qc}from"./chunk-B266DDBJ.js";import{Ad as Pt,Ba as $c,Bb as Fc,Ca as Dt,Cb as Uc,Cc as dd,Dc as de,Ea as Tc,Fa as A,Fd as ud,Ga as Dc,Ha as xe,Id as md,Ja as Mi,Jd as pd,Ka as Oc,Kb as Hc,Kd as ie,La as $a,Lb as Ot,Ma as Ta,Na as Da,Nb as Oa,O as Sc,Ob as zc,Pa as Pc,Pb as Bt,Qa as Lc,R as xc,Rb as Be,T as Ca,Ta as Nc,Tb as Je,Wb as id,Y as ue,Yb as zi,Z as qe,Zb as rd,_ as Ic,_b as ad,a as _c,aa as Y,ac as od,bb as Mc,d as gc,da as Rc,e as yc,ic as F,kb as jc,mc as K,o as Aa,oa as Ac,oc as Ne,pa as Cc,pc as sd,qa as H,qc as Wi,va as Nn,wa as M,wd as T,xa as Ge,xc as cd,xd as ld,ya as Ni,yd as Zt,za as Gt,zd as wt}from"./chunk-NLZUI234.js";import{a as qn}from"./chunk-VVRXF4JO.js";import{A as Ln,B as D,C as gt,D as j,E as B,H as Z,a as Oi,d as Pi,o as wc,q as vc,s as bc,u as kc,v as Li,w as Ec,y,z as g}from"./chunk-KTXU5WU6.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 dn(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 Xa(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 sg}from"node:crypto";import cg 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 ln=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 Ol=1,Mt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Za=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],dg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],lg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,fr=30,hr=5e3,Pl=4,ug=50;function ot(e,t){if(!lg.test(e))throw new L(`${t} must be a stable lowercase id`)}function mg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Gn(e){let t=dg.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 eo(e,t){return A(e)===A(t)}function Ll(e,t){if(t.polarity==="equals")return eo(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 Nl(e){let t=Gn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Ll(i.observed,t)===(i.expected==="pass"))}function pg(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!eo(e.value,t.value)}function fg(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 pg(Gn(e),Gn(t))||n[t.enforcement]<n[e.enforcement]||i}function hg(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 _g(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 gg(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 to(e){ot(e.id,"measurement.id"),e.max_cost!==void 0&&mg(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 ${Za.join(", ")}`);let n=Reflect.get(t,"kind");if(!Za.includes(n))throw new L(`measurement.source.kind must be one of ${Za.join(", ")}`);let i=t;if(i.kind==="items"&&hg(i),i.kind==="dependency_kind"&&_g(i),i.kind==="prose_edge_gap"&&gg(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 no(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=Gn(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(!Nl(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function yg(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(!Mt.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 Ml(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 ${Mt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Mt.includes(t))throw new L(`gate trigger must be one of ${Mt.join(", ")}`);return e.provider_policy&&yg(e.provider_policy),e}function un(e){if(e.version!==Ol)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(to(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(no(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){Ml(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 jl(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function io(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)io(n,t)}function jl(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=[];io(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function wg(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"&&io(o.source.expression,n)}return r}function Bn(){return{version:Ol,measurements:[],assertions:[],gates:[]}}function vg(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 eo(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function bg(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 kg(e,t){let n=[],i=Ca(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=Ca(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&bg(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 Eg(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 Sg(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 Qa(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function xg(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(Qa(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(Qa(o.id,s));for(let s of Eg(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 Ig(e,t){let n=xg(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=Qa(o.holder_id,d);if(n.linked_pairs.has(l)||Sg(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 Rg(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 Ag(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 Cg(e,t){let n=e.source;return n.kind==="items"?vg(n,t):n.kind==="dependency_kind"?kg(n,t):n.kind==="prose_edge_gap"?Ig(n,t):n.kind==="history"?Rg(n,t):n.kind==="links"?Ag(n,t):null}function Fl(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 Ul(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 Hl(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 zl(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 Ul(e.operands,Pl,o=>Hl(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 Tg(e,t,n,i,r){to(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await Hl(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=Cg(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=Fl([...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:${sg("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 zl(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=Tg(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 ro(e,t,n=[e]){return zl(e,t,n,[],{cache:new Map,charged:new Set})}function Dg(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 Og(e,t,n={}){no(e);let i=Gn(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:Dg(t.value,i),verdict:r?"retired":Ll(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Nl(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Pg(e,t,n,i){let r=wg(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 Dl(e,t,n,i,r){try{return await ro(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 Wl(e,t,n,i){un(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}`);Pg(r,t,n,i.trigger);let a=await Ul(r.assertion_ids,Pl,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 Dl(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 Og(d,await Dl(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:Fl(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function _r(e){return cg.join(e,"assurance.json")}async function ql(e){let t=await B(_r(e));return t===null?Bn():gr(t)}function gr(e){try{return un(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 yr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Lg(e,t){e==="measurement"?to(t):e==="assertion"?no(t):Ml(t)}async function Jn(e,t){let n=structuredClone(yr(await ql(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Gl(e,t,n){let i=yr(await ql(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function wr(e,t,n,i={}){Lg(t,n);let r=await $(e),a=z(i.author,r.author_default),o=await tn({pmRoot:e,filePath:_r(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:fr,lockWaitMs:hr,mutate:s=>{let c=s===null?Bn():gr(s),d=yr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&fg(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),un(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
2
|
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function ao(e,t,n={}){let i=Bn();i.measurements=structuredClone(t.measurements),i.assertions=structuredClone(t.assertions),i.gates=structuredClone(t.gates),un(i);let r=await $(e),a=z(n.author,r.author_default),o=await tn({pmRoot:e,filePath:_r(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:fr,lockWaitMs:hr,mutate:s=>{let c=s===null?Bn():gr(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"),un(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
3
|
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Bl(e,t,n,i={}){let r=await $(e),a=z(i.author,r.author_default),o=await tn({pmRoot:e,filePath:_r(e),op:`assurance:${t}:remove`,author:a,message:i.message,lockTtlSeconds:fr,lockWaitMs:hr,mutate:s=>{let c=s===null?Bn():gr(s);if(t==="measurement"){let u=jl(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=yr(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),un(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
4
|
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function Jl(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await $(e);await sr({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:fr,lockWaitMs:hr})}async function Vl(e,t={}){let n=t.limit??ug;if(!Number.isInteger(n)||n<1||n>ln)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${ln}`);return(await nt(or(e),re)).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)}(function(){try{var e=typeof window<"u"?window:typeof 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 Vn={type:"string",minLength:1,maxLength:128,pattern:"\\S"},vr={type:"array",minItems:1,maxItems:$a,items:Vn},Kl={...vr,items:{...Vn,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Ng={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,vr])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:Vn,id:Vn}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Kl}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:vr}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Kl,authors:vr}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:$a,items:{type:"array",minItems:2,maxItems:2,items:Vn}}}}]}}},OC={$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:Oc,items:Ng}}};(function(){try{var e=typeof window<"u"?window:typeof 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 Yl(e,t,n,i){let r=await kt(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"]}:Xl(r,t,n,i)}function Mg(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Xl(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=Nc(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:Mg(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 jg 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 Fg(){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 eu(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 Ug(e,t){let n=M(process.cwd(),e.path);await te(n);let i=await $(n);return{pmRoot:n,settings:i,author:z(t,i.author_default)}}function Zl(e,t,n,i){if(e==="policy-mode")return Da({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let a=Ta(i.definition),o=Da({...n,policies:[...r,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
@@ -22,8 +22,8 @@ import{c as Et,d as on,e as sn,f as cn,g as Cl,j as Tl}from"./chunk-HMYDUEQK.js"
|
|
|
22
22
|
Agent guidance check
|
|
23
23
|
`),Ir.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
24
24
|
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Ir.write(`
|
|
25
|
-
`),Uy(n,!0)}finally{t.close()}}function Nu(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:yo,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 Mu(e){let t=[],n=await Lu(e);for(let i of Ay){let r=se.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 go.readFile(r,"utf8"),s=o.toLowerCase(),c=Cy.filter(l=>s.includes(l)),d=Ly(o);t.push({file_path:r,exists:a,has_guidance:d||c.length>=$y,has_marker:d,outdated:d&&Pu(o,n).changed})}return t}function jt(e,t){e.includes(t)||e.push(t)}function zy(e,t){let n=Nu(e),i=JSON.stringify(n)!==JSON.stringify(t);return i&&(e.agent_guidance=t),{changed:i,state:t}}async function ju(e,t=se.dirname(e)){let n=await D(e)?await go.readFile(e,"utf8"):"",i=Pu(n,await Lu(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 Wy(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=>mn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>mn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>mn(e.projectRoot,t.file_path))}}async function qy(e,t,n){return e?await Mu(n):t}function ei(e,t,n){e.state={...e.state,...n,template_version:yo,last_checked_files:t}}async function Fu(e,t){if(t.presentBefore)return;let n=await ju(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Gy(e,t){t||(e.warnings.push("agent_guidance:missing"),jt(e.nextSteps,ti))}function By(e,t){e.skipped=!0,ei(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),jt(e.nextSteps,ti)}async function Jy(e,t){await Fu(e,t),ei(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Vy(e,t){e.state.declined&&ei(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Ky(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),jt(e.nextSteps,ti)}async function Yy(e,t){if(e.prompted=!0,await Hy(t.targetRelativePath)){await Fu(e,t),ei(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ei(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),jt(e.nextSteps,ti)}function Xy(e){e.warnings.push("agent_guidance:missing_non_interactive"),jt(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),jt(e.nextSteps,ti)}async function Zy(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Gy(n,t.presentBefore),n):t.mode==="skip"?(By(n,t.checkedFiles),n):t.mode==="add"?(await Jy(n,t),n):t.presentBefore?(Vy(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Ky(n),n):t.interactive?(await Yy(n,t),n):(Xy(n),n)}async function Uu(e){let t=jy(e.pm_root,e.cwd),n=await Mu(t),i=Fy(n,t),r=mn(t,i),a=n.map(l=>mn(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await Zy(Nu(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 ju(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=zy(e.settings,s.state);n=await qy(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>mn(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),jt(s.nextSteps,"pm init --agent-guidance add")),{summary:Wy({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 ni(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 ${de(["package","activate",o,`--${a}`])}.`:`Package ${o} requires ${d}. Use a compatible host or package version, or keep it disabled with ${de(["package","deactivate",o,`--${a}`])}.`}import ht from"node:fs/promises";import be from"node:path";import ii from"node:fs/promises";import{createHash as Qy}from"node:crypto";import zu 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 wo=new Set([void 0,...Rd]),Wu=11,ew="history-drift-cache.json";function qu(e){return zu.join(e,"runtime",ew)}async function tw(e){try{let t=await ii.readFile(qu(e),"utf8"),n=JSON.parse(t);return n.version!==Wu||n.history_item_hash_version!==Qi||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(i=>typeof i.chain_ok!="boolean"||typeof i.latest_hash_comparable!="boolean"||!wo.has(i.hash_algorithm)||!Qt.includes(i.item_hash_version)&&i.version_skew!==!0||i.chain_ok&&i.version_skew!==!0&&Qt.includes(i.item_hash_version)&&!i.latest_hash_comparable)?null:n}catch{return null}}function Gu(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Bu(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?[re]:[]])].sort((n,i)=>n.localeCompare(i));return{...e,driftedItems:t}}async function nw(e,t,n,i,r){let a=or(e),o;try{o=await ii.stat(a)}catch(d){return j(d)||r.unreadableStreams.push(re),!1}let s=r.missingStreams.length,c=await Ju({itemId:re,historyPath:a,stat:o,cached:t[re],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.versionSkew&&r.versionSkews.push(re),c.verification.chainOk||r.chainMismatches.push(re),n[re]={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!wo.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!Qt.includes(e.item_hash_version)}async function rw(e){let t=await ii.readFile(e,"utf8"),n=Qy("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(iw),s=i[i.length-1],c=wo.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&Qt.includes(d),u=l?d:a.item_hash_version;return{latestAfterHash:r,hashAlgorithm:c?Re(s.hash_algorithm):void 0,identityDiscontinuities:Ad(i),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??Qi}}function aw(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Hu(e,t,n){try{return await rw(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function ow(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 Ju(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 Hu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await Hu(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!ow(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&&Qt.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Vu(e,t,n,i){let r,a;try{r=Dt(e,t.id),a=await ii.stat(r)}catch(d){return(j(d)?i.missingStreams:i.unreadableStreams).push(t.id),!1}let o=await Ju({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&&(Fd({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||i.hashMismatches.push(t.id)),o.cacheDirty}async function sw(e,t){if(!(t.unreadableStreams.includes(re)||t.chainMismatches.includes(re)||t.versionSkews.includes(re)))try{let n=await qd(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(re)}}async function Ku(e,t){let n=Gu();return await Vu(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Bu(n)}async function Ft(e,t,n={}){let i=Gu(),r=(await tw(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:r,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await Vu(e,l,c,i)&&(o=!0);let d=await nw(e,r,a,s,i);if(o||=d,await sw(e,i),o||Object.keys(r).length!==Object.keys(a).length){let l=qu(e);try{await ii.mkdir(zu.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:Wu,history_item_hash_version:Qi,entries:a}))}catch{}}return Bu(i)}import pn from"node:fs/promises";import Rr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b4ef85f-d844-53e3-ba32-08b95377584a")}catch{}})();function Yu(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 cw(e,t,n){let i=Yu(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 Xu(e,t,n){let i=cw(e,t,n);if(i.detail!=="active")return i;let r=Yu(t),a=await ud(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 md(e,"gc");if(i===null)return!1;try{let r;try{r=await pn.readFile(e,"utf8")}catch(a){if(j(a))return!0;throw a}if(r!==t)return!1;n&&await pd(e,t);try{await pn.unlink(e)}catch(a){if(!j(a))throw a}return!0}finally{await i()}}function lw(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 Zu(e,t){let n=t??Date.now(),i=Rr.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 pn.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 pn.readFile(Rr.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 Xu(o,s,n);lw(r,c,d)}return r}async function uw(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 Qu(e,t){let{hooks:n}=t,i=t.now??Date.now(),r=Rr.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},o;try{o=(await pn.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=Rr.join(r,s),d=`locks/${s}`;if(n?.onRead){let m=await n.onRead(c);a.warnings.push(...m)}let l;try{l=await pn.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 Xu(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 uw(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 mw=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 vo(e){if(typeof e!="string")return;let t=e.trim();for(let n of mw)if(t===n.code||t.startsWith(`${n.code}:`))return n}function bo(e){let t={};for(let n of e){let i=vo(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function em(e){return Object.values(bo(e))}import En 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 pw=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function fn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(zi(t.extensionName));for(let _ of t.extensionNames??[])n.add(zi(_));let i=_=>n.size===0||n.has(zi(_)),r=(_,w)=>tm(_.filter(v=>i(v.name)).map(w)),a=(_,w)=>tm(_.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:rd(e,t),commands:r(o.commands,_=>_.command),command_overrides:r(s.overrides,_=>_.command),command_handlers:r(s.handlers,_=>_.command),hooks:pw.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 tm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import iv from"node:path";import{mkdir as rv}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 fw=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function hw(e){let t=fw.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function _w(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function nm(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=hw(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=_w(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:Wc(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as pm}from"node:crypto";import _n from"node:fs/promises";import gn from"node:path";import{mkdir as gw,readFile as yw}from"node:fs/promises";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]="1fae5539-4eb8-5eba-bfd6-a191c89448ec")}catch{}})();var ko=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ww="sdk-workspace-transaction",vw=/^[a-zA-Z0-9._-]+$/,bw=30,kw=3e3;function sm(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!vw.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function im(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 Ew(e){return{pmRoot:im(e.pmRoot,"Transaction pmRoot"),transactionId:sm(e.transactionId,"Transaction id"),author:im(e.author,"Transaction author")}}function rm(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 cm(e,t){return om.join(e,"transactions","sdk",`${t}.json`)}async function St(e,t){t.updatedAt=T();let n=cm(e,t.transactionId);await gw(om.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
|
|
26
|
-
`)}function Sw(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Ut(e){return Object.assign(Object.create(null),e)}function xw(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 Eo(e,t){return e===void 0?void 0:xw(e,t)}function So(e,t,n,i){let r=Eo(n,i);r===void 0?delete e[t]:e[t]=r}function am(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xo(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Iw(e,t){if(!xo(e.startedStepIds,t)||!xo(e.completedStepIds,t)||!am(e.results)||!am(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 Ar(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 Rw(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 Aw(e,t,n){let i;try{i=JSON.parse(e)}catch{throw Ar(t,"invalid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw Ar(t,"expected an object");let r=i;if(!(r.schemaVersion===1&&r.transactionId===t))throw Ar(t,"schema version or transaction id does not match the journal file");let a=r.stepIds;if(!Array.isArray(a)||!xo(a,a)||!Iw(r,a)||!Sw(r)||typeof r.status!="string"||!["applying","compensating","compensated","committed"].includes(r.status))throw Ar(t,"invalid lifecycle, metadata, status or step ids");if(!(r.status==="compensated"||a.length===n.length&&a.every((o,s)=>o===n[s])))throw Rw(t);return{...r,results:Ut(r.results),compensationData:Ut(r.compensationData)}}async function Cw(e,t,n,i,r){let a=r,o=a!==void 0;if(a?.status==="compensating"&&await dm(e,a),a===void 0||a.status==="compensated"){let s=T();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:Ut(),compensationData:Ut()},await St(e.pmRoot,a),await st(e,a,"prepared")}return{journal:a,recovered:o}}async function $w(e,t,n){try{await Dw(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=Eo(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();So(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=Eo(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)),So(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:Ut(t.results)}}catch(i){if(i instanceof ko||t.status==="committed")throw i;try{await dm(e,t)}catch(r){throw new AggregateError([i,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw i}}async function Tw(e,t,n){try{return Aw(await yw(cm(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 Dw(e,t){let n=new Set,i=Ut();for(let r of t){let a=await r.inspect();a.state==="applied"&&(n.add(r.id),So(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 dm(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{a=i.has(r.id)&&(await r.inspect()).state==="applied"}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 lm(e){let{pmRoot:t,transactionId:n,author:i}=Ew(e),r=rm(e.lockTtlSeconds,bw,"Transaction lock TTL"),a=rm(e.lockWaitMs,kw,"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=sm(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 ie(t,ww,r,i,!1,!1,a);try{let l=await Tw(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Ut(l.results)};let m=await Cw(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 fm(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 hm(e,t){let n=Ro(e),i=ct(t,"migrationScope");return`auto-${pm("sha256").update(JSON.stringify({scope:i,request:n})).digest("hex").slice(0,20)}`}function Ro(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:oe(ct(e.from,"source")),to:oe(ct(e.to,"target")),...e.type===void 0?{}:{type:ct(e.type,"type")}}:{kind:e.kind,from:oe(ct(e.from,"source")),to:oe(ct(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Ow(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Pw(e,t,n){let i=Ie(t.schema),r=Ow(n);return Ve(e,i.files[r],$e[r])}function _m(e,t){return gn.join(e,"transactions","schema",`${t}-plan.json`)}function Cr(e){return e.length===0?null:JSON.parse(e)}async function hn(e){let t=await B(e);return{exists:t!==null,raw:t??""}}async function gm(e,t){t.exists?await Z(e,t.raw):await _n.rm(e,{force:!0})}function Lw(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 Nw(e,t,n){let i=Vt(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 Kt(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 Kt(i)}function Mw(e,t,n){let i=Yt(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 Xt(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 Xt(i)}function jw(e,t,n){return t.kind==="rename-type"?Lw(e,t,n):t.kind==="rename-field"?Nw(e,t,n):Mw(e,t,n)}function xt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function yn(e){return Array.isArray(e)?e.map(t=>Ao(t)).filter(t=>t!==void 0):[]}function Fw(e,t){for(let n of yn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(i=>xt(i,t)));for(let n of yn(e.type_workflows))n.type=xt(n.type,t)}function Uw(e,t){for(let i of yn(e.definitions))i.default_status=xt(i.default_status,t);let n=Ao(e.workflow);if(n)for(let[i,r]of Object.entries(n))n[i]=xt(r,t);for(let i of yn(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 Hw(e,t){for(let n of yn(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 yn(n[i])){let a=i==="options"?"key":"option";r[a]=xt(r[a],t)}}}function zw(e,t){let n=Ao(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 Io(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"?Fw(i,t):t.kind==="rename-field"?Hw(i,t):Uw(i,t),zw(i,t),`${JSON.stringify(i,null,2)}
|
|
25
|
+
`),Uy(n,!0)}finally{t.close()}}function Nu(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:yo,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 Mu(e){let t=[],n=await Lu(e);for(let i of Ay){let r=se.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 go.readFile(r,"utf8"),s=o.toLowerCase(),c=Cy.filter(l=>s.includes(l)),d=Ly(o);t.push({file_path:r,exists:a,has_guidance:d||c.length>=$y,has_marker:d,outdated:d&&Pu(o,n).changed})}return t}function jt(e,t){e.includes(t)||e.push(t)}function zy(e,t){let n=Nu(e),i=JSON.stringify(n)!==JSON.stringify(t);return i&&(e.agent_guidance=t),{changed:i,state:t}}async function ju(e,t=se.dirname(e)){let n=await D(e)?await go.readFile(e,"utf8"):"",i=Pu(n,await Lu(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 Wy(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=>mn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>mn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>mn(e.projectRoot,t.file_path))}}async function qy(e,t,n){return e?await Mu(n):t}function ei(e,t,n){e.state={...e.state,...n,template_version:yo,last_checked_files:t}}async function Fu(e,t){if(t.presentBefore)return;let n=await ju(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Gy(e,t){t||(e.warnings.push("agent_guidance:missing"),jt(e.nextSteps,ti))}function By(e,t){e.skipped=!0,ei(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),jt(e.nextSteps,ti)}async function Jy(e,t){await Fu(e,t),ei(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Vy(e,t){e.state.declined&&ei(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Ky(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),jt(e.nextSteps,ti)}async function Yy(e,t){if(e.prompted=!0,await Hy(t.targetRelativePath)){await Fu(e,t),ei(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ei(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),jt(e.nextSteps,ti)}function Xy(e){e.warnings.push("agent_guidance:missing_non_interactive"),jt(e.nextSteps,"Inspect workflow guidance: pm init --agent-guidance status"),jt(e.nextSteps,ti)}async function Zy(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Gy(n,t.presentBefore),n):t.mode==="skip"?(By(n,t.checkedFiles),n):t.mode==="add"?(await Jy(n,t),n):t.presentBefore?(Vy(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Ky(n),n):t.interactive?(await Yy(n,t),n):(Xy(n),n)}async function Uu(e){let t=jy(e.pm_root,e.cwd),n=await Mu(t),i=Fy(n,t),r=mn(t,i),a=n.map(l=>mn(t,l.file_path)),o=n.some(l=>l.has_guidance),s=await Zy(Nu(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 ju(l.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=zy(e.settings,s.state);n=await qy(s.applied,n,t);let d=n.filter(l=>l.outdated).map(l=>mn(t,l.file_path));return d.length>0&&(s.warnings.push(`agent_guidance_outdated:${d.join(",")}`),jt(s.nextSteps,"pm init --agent-guidance add")),{summary:Wy({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 ni(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 ${de(["package","activate",o,`--${a}`])}.`:`Package ${o} requires ${d}. Use a compatible host or package version, or keep it disabled with ${de(["package","deactivate",o,`--${a}`])}.`}import ht from"node:fs/promises";import be from"node:path";import ii from"node:fs/promises";import{createHash as Qy}from"node:crypto";import zu 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 wo=new Set([void 0,...Rd]),Wu=11,ew="history-drift-cache.json";function qu(e){return zu.join(e,"runtime",ew)}async function tw(e){try{let t=await ii.readFile(qu(e),"utf8"),n=JSON.parse(t);return n.version!==Wu||n.history_item_hash_version!==Qi||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(i=>typeof i.chain_ok!="boolean"||typeof i.latest_hash_comparable!="boolean"||!wo.has(i.hash_algorithm)||!Qt.includes(i.item_hash_version)&&i.version_skew!==!0||i.chain_ok&&i.version_skew!==!0&&Qt.includes(i.item_hash_version)&&!i.latest_hash_comparable)?null:n}catch{return null}}function Gu(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function Bu(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?[re]:[]])].sort((n,i)=>n.localeCompare(i));return{...e,driftedItems:t}}async function nw(e,t,n,i,r){let a=or(e),o;try{o=await ii.stat(a)}catch(d){return j(d)||r.unreadableStreams.push(re),!1}let s=r.missingStreams.length,c=await Ju({itemId:re,historyPath:a,stat:o,cached:t[re],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.versionSkew&&r.versionSkews.push(re),c.verification.chainOk||r.chainMismatches.push(re),n[re]={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!wo.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!Qt.includes(e.item_hash_version)}async function rw(e){let t=await ii.readFile(e,"utf8"),n=Qy("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(iw),s=i[i.length-1],c=wo.has(s.hash_algorithm),d=s.item_hash_version,l=d!==void 0&&Qt.includes(d),u=l?d:a.item_hash_version;return{latestAfterHash:r,hashAlgorithm:c?Re(s.hash_algorithm):void 0,identityDiscontinuities:Ad(i),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||l||d===void 0),contentHash:n,itemHashVersion:u??Qi}}function aw(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Hu(e,t,n){try{return await rw(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function ow(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 Ju(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 Hu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await Hu(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!ow(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&&Qt.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function Vu(e,t,n,i){let r,a;try{r=Dt(e,t.id),a=await ii.stat(r)}catch(d){return(j(d)?i.missingStreams:i.unreadableStreams).push(t.id),!1}let o=await Ju({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&&(Fd({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||i.hashMismatches.push(t.id)),o.cacheDirty}async function sw(e,t){if(!(t.unreadableStreams.includes(re)||t.chainMismatches.includes(re)||t.versionSkews.includes(re)))try{let n=await qd(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(re)}}async function Ku(e,t){let n=Gu();return await Vu(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),Bu(n)}async function Ft(e,t,n={}){let i=Gu(),r=(await tw(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:r,nextEntries:a,verifyCacheHitByContent:s};for(let l of t)await Vu(e,l,c,i)&&(o=!0);let d=await nw(e,r,a,s,i);if(o||=d,await sw(e,i),o||Object.keys(r).length!==Object.keys(a).length){let l=qu(e);try{await ii.mkdir(zu.dirname(l),{recursive:!0}),await Z(l,JSON.stringify({version:Wu,history_item_hash_version:Qi,entries:a}))}catch{}}return Bu(i)}import pn from"node:fs/promises";import Rr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b4ef85f-d844-53e3-ba32-08b95377584a")}catch{}})();function Yu(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 cw(e,t,n){let i=Yu(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 Xu(e,t,n){let i=cw(e,t,n);if(i.detail!=="active")return i;let r=Yu(t),a=await ud(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 md(e,"gc");if(i===null)return!1;try{let r;try{r=await pn.readFile(e,"utf8")}catch(a){if(j(a))return!0;throw a}if(r!==t)return!1;n&&await pd(e,t);try{await pn.unlink(e)}catch(a){if(!j(a))throw a}return!0}finally{await i()}}function lw(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 Zu(e,t){let n=t??Date.now(),i=Rr.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 pn.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 pn.readFile(Rr.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 Xu(o,s,n);lw(r,c,d)}return r}async function uw(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 Qu(e,t){let{hooks:n}=t,i=t.now??Date.now(),r=Rr.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},o;try{o=(await pn.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=Rr.join(r,s),d=`locks/${s}`;if(n?.onRead){let m=await n.onRead(c);a.warnings.push(...m)}let l;try{l=await pn.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 Xu(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 uw(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 mw=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 vo(e){if(typeof e!="string")return;let t=e.trim();for(let n of mw)if(t===n.code||t.startsWith(`${n.code}:`))return n}function bo(e){let t={};for(let n of e){let i=vo(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function em(e){return Object.values(bo(e))}import En 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 pw=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function fn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(zi(t.extensionName));for(let _ of t.extensionNames??[])n.add(zi(_));let i=_=>n.size===0||n.has(zi(_)),r=(_,w)=>tm(_.filter(v=>i(v.name)).map(w)),a=(_,w)=>tm(_.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:rd(e,t),commands:r(o.commands,_=>_.command),command_overrides:r(s.overrides,_=>_.command),command_handlers:r(s.handlers,_=>_.command),hooks:pw.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 tm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import iv from"node:path";import{mkdir as rv}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 fw=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function hw(e){let t=fw.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function _w(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function nm(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=hw(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=_w(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:Wc(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as pm}from"node:crypto";import _n from"node:fs/promises";import gn from"node:path";import{mkdir as gw,readFile as yw}from"node:fs/promises";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]="d913251a-fc99-5767-b19d-ae9473adc138")}catch{}})();var ko=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ww="sdk-workspace-transaction",vw=/^[a-zA-Z0-9._-]+$/,bw=30,kw=3e3;function sm(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!vw.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function im(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 Ew(e){return{pmRoot:im(e.pmRoot,"Transaction pmRoot"),transactionId:sm(e.transactionId,"Transaction id"),author:im(e.author,"Transaction author")}}function rm(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 cm(e,t){return om.join(e,"transactions","sdk",`${t}.json`)}async function St(e,t){t.updatedAt=T();let n=cm(e,t.transactionId);await gw(om.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
|
|
26
|
+
`)}function Sw(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Ut(e){return Object.assign(Object.create(null),e)}function xw(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 Eo(e,t){return e===void 0?void 0:xw(e,t)}function So(e,t,n,i){let r=Eo(n,i);r===void 0?delete e[t]:e[t]=r}function am(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xo(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Iw(e,t){if(!xo(e.startedStepIds,t)||!xo(e.completedStepIds,t)||!am(e.results)||!am(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 Ar(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 Rw(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 Aw(e,t,n){let i;try{i=JSON.parse(e)}catch{throw Ar(t,"invalid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw Ar(t,"expected an object");let r=i;if(!(r.schemaVersion===1&&r.transactionId===t))throw Ar(t,"schema version or transaction id does not match the journal file");let a=r.stepIds;if(!Array.isArray(a)||!xo(a,a)||!Iw(r,a)||!Sw(r)||typeof r.status!="string"||!["applying","compensating","compensated","committed"].includes(r.status))throw Ar(t,"invalid lifecycle, metadata, status or step ids");if(!(r.status==="compensated"||a.length===n.length&&a.every((o,s)=>o===n[s])))throw Rw(t);return{...r,results:Ut(r.results),compensationData:Ut(r.compensationData)}}async function Cw(e,t,n,i,r){let a=r,o=a!==void 0;if(a?.status==="compensating"&&await dm(e,a),a===void 0||a.status==="compensated"){let s=T();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:Ut(),compensationData:Ut()},await St(e.pmRoot,a),await st(e,a,"prepared")}return{journal:a,recovered:o}}async function $w(e,t,n){try{await Dw(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=Eo(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();So(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=Eo(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)),So(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:Ut(t.results)}}catch(i){if(i instanceof ko||t.status==="committed")throw i;try{await dm(e,t)}catch(r){throw new AggregateError([i,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw i}}async function Tw(e,t,n){try{return Aw(await yw(cm(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 Dw(e,t){let n=new Set,i=Ut();for(let r of t){let a=await r.inspect();a.state==="applied"&&(n.add(r.id),So(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 dm(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 lm(e){let{pmRoot:t,transactionId:n,author:i}=Ew(e),r=rm(e.lockTtlSeconds,bw,"Transaction lock TTL"),a=rm(e.lockWaitMs,kw,"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=sm(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 ie(t,ww,r,i,!1,!1,a);try{let l=await Tw(t,n,s),u=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Ut(l.results)};let m=await Cw(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 fm(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 hm(e,t){let n=Ro(e),i=ct(t,"migrationScope");return`auto-${pm("sha256").update(JSON.stringify({scope:i,request:n})).digest("hex").slice(0,20)}`}function Ro(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:oe(ct(e.from,"source")),to:oe(ct(e.to,"target")),...e.type===void 0?{}:{type:ct(e.type,"type")}}:{kind:e.kind,from:oe(ct(e.from,"source")),to:oe(ct(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Ow(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Pw(e,t,n){let i=Ie(t.schema),r=Ow(n);return Ve(e,i.files[r],$e[r])}function _m(e,t){return gn.join(e,"transactions","schema",`${t}-plan.json`)}function Cr(e){return e.length===0?null:JSON.parse(e)}async function hn(e){let t=await B(e);return{exists:t!==null,raw:t??""}}async function gm(e,t){t.exists?await Z(e,t.raw):await _n.rm(e,{force:!0})}function Lw(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 Nw(e,t,n){let i=Vt(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 Kt(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 Kt(i)}function Mw(e,t,n){let i=Yt(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 Xt(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 Xt(i)}function jw(e,t,n){return t.kind==="rename-type"?Lw(e,t,n):t.kind==="rename-field"?Nw(e,t,n):Mw(e,t,n)}function xt(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function yn(e){return Array.isArray(e)?e.map(t=>Ao(t)).filter(t=>t!==void 0):[]}function Fw(e,t){for(let n of yn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(i=>xt(i,t)));for(let n of yn(e.type_workflows))n.type=xt(n.type,t)}function Uw(e,t){for(let i of yn(e.definitions))i.default_status=xt(i.default_status,t);let n=Ao(e.workflow);if(n)for(let[i,r]of Object.entries(n))n[i]=xt(r,t);for(let i of yn(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 Hw(e,t){for(let n of yn(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 yn(n[i])){let a=i==="options"?"key":"option";r[a]=xt(r[a],t)}}}function zw(e,t){let n=Ao(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 Io(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"?Fw(i,t):t.kind==="rename-field"?Hw(i,t):Uw(i,t),zw(i,t),`${JSON.stringify(i,null,2)}
|
|
27
27
|
`}function ym(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=Vt(e).fields;return{source:i.some(r=>r.key===t.from),target:i.some(r=>r.key===t.to)}}let n=Yt(e).statuses;return{source:n.some(i=>i.id===t.from),target:n.some(i=>i.id===t.to)}}function Ww(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 qw(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 wm(e,t){let n=Ro(t.request),i=t.migrationId===void 0?hm(n,t.migrationScope??"plan"):fm(t.migrationId),r=e.map(c=>qw(c,n)).filter(c=>c!==null).sort((c,d)=>c.id.localeCompare(d.id)),a=pm("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 Gw(e){let t=H(e.settings,F()),n=[...new Set(Object.values(t.type_to_folder))],i=await lr(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 tl({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 Bw(e,t){let n=await B(_m(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: ${Rc(i)}`,y.GENERIC_FAILURE)}}async function Jw(e,t){let n=_m(e,t.migration_id);await _n.mkdir(gn.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
28
|
`)}function Vw(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function Kw(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 um(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 mm(e){return{id:e.id,inspect:async()=>{let t=await hn(e.filePath),n=ym(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 hn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await hn(e.filePath);return await Z(e.filePath,jw(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 gm(e.filePath,{exists:t.exists,raw:t.raw})}}}function Yw(e){return{id:e.stepId,inspect:async()=>{let t=await hn(e.filePath);return{state:Io(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await hn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await hn(e.filePath);return await Z(e.filePath,Io(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 gm(e.filePath,{exists:t.exists,raw:t.raw})}}}function Xw(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await $(e.pmRoot),n=H(t,F()).type_to_folder,i=await Kw({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),r=Ww(i,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await $(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:um(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:i.changedFields}},compensate:async()=>{let t=await $(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:um(i,e.request,"reverse")}}})}}}async function Zw(e){let t=await Bw(e.pmRoot,e.migrationId);if(t){if(!Vw(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 Gw({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...wm(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function Qw(e){let t=ym(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 Jw(e.pmRoot,e.plan)}async function ev(e){let t=Ie(e.settings.schema),n=[...new Set([["types",$e.types],["fields",$e.fields],["workflows",$e.workflows]].map(([r,a])=>Ve(e.pmRoot,t.files[r],a)).filter(r=>r!==e.schemaPath))];try{let r=gn.join(e.pmRoot,"templates"),a=await _n.readdir(r,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>gn.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&&Io(a,e.request)!==a&&i.push({filePath:r,beforeRaw:a})}return{paths:n,snapshots:i}}async function tv(e){for(let t of e.snapshots){let n=await _n.readFile(t.filePath,"utf8"),i=gn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Wa({pmRoot:e.pmRoot,author:e.author,documentPath:i,before:Cr(t.beforeRaw),after:Cr(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 nv(e,t,n){let i=Ro(e),r=M(process.cwd(),n.path);await te(r);let a=t.migrationId===void 0?hm(i,await _n.realpath(r)):fm(t.migrationId),o=await $(r),s=z(t.author,o.author_default),c=await Zw({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=Pw(r,o,i),u=await B(l)??"";c.stored||await Qw({pmRoot:r,schemaPath:l,request:i,plan:d});let m=await ev({pmRoot:r,schemaPath:l,settings:o,request:i}),f=[mm({id:"stage-schema",filePath:l,request:i,phase:"stage"}),...m.paths.map((w,v)=>Yw({filePath:w,request:i,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...d.items.map(w=>Xw({pmRoot:r,id:w.id,request:i,author:s,force:t.force===!0})),mm({id:"retire-source",filePath:l,request:i,phase:"retire"})],p=await lm({pmRoot:r,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),h=await _n.readFile(l,"utf8"),{historyPath:_}=await Wa({pmRoot:r,author:s,documentPath:gn.relative(r,l).replaceAll("\\","/"),before:Cr(u),after:Cr(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 tv({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 OD=[...Mi,"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"],$r="schema-types",vm="schema-statuses",bm="schema-fields";function It(e){return nn({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 ND(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{r=La({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 $(i),o=Ie(a.schema),s=Ve(i,o.files.types,$e.types),c=[],d=z(t.author,a.author_default),l=Me(a),u=await ie(i,$r,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{qc(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)}Gc(r,p,h)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}m=Ui(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 ri(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 km(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:T()}}async function dt(e){await te(e)}async function km(e,t){try{let n=await Cl(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 av(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 ov(e,t,n,i){let r=H(t,F()),a=fe(n),o=oe(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(oe(c))??oe(c))===o}).length}async function sv(e,t,n,i,r){if(r.length===0||Ma.has(r))return;let a=await ov(t,n,i,r);a>0&&e.push(`items_using_status:${a}`);let o=cv(i.workflow,r);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function cv(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&&oe(n)===t).map(([n])=>n)}async function MD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r=await $(i),a=Ie(r.schema),o=Ve(i,a.files.types,$e.types),s=[],c=z(t.author,r.author_default),d=Me(r),l=await ie(i,$r,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=Bc(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 av(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 km(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:T()}}function Co(e,t){return Ve(e,t.files.statuses,$e.statuses)}function Tr(e,t){return Ve(e,t.files.fields,$e.fields)}function Em(e,t){return Ve(e,t.files.types,$e.types)}async function ri(e,t,n,i){for(let r of t){let a=Cc(r.folder??Ac(r.name)),o=iv.join(e,a);await D(o)||(await rv(o,{recursive:!0}),n.push(...await K({path:o,scope:"project",op:i})))}}function $o(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 dv(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 lv(e){let t=new Map;for(let n of e){let i=oe(n.id);if(i.length!==0){t.set(i,i);for(let r of Array.isArray(n.aliases)?n.aliases:[]){let a=oe(r);a.length>0&&!t.has(a)&&t.set(a,i)}}}return t}async function jD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{r=ed({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 $(i),o=Ie(a.schema),s=Co(i,o),c=fe(o);try{ja(r,c.alias_to_id)}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let d=dv(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 "${Jt(r.id)}" --role active`,`pm schema add-status "${Jt(r.id)}" --role blocked`]});let l=[],u=z(t.author,a.author_default),m=Me(a),f=await ie(i,vm,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{_=Yt(h)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.GENERIC_FAILURE)}let w=lv(_.statuses);try{ja(r,w)}catch(v){throw new g(v instanceof Error?v.message:String(v),y.USAGE)}p=td(_,r,d),await It({pmRoot:i,filePath:s,raw:Xt(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:T()}}async function FD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r=await $(i),a=Ie(r.schema),o=Co(i,a),s=[],c=z(t.author,r.author_default),d=Me(r),l=await ie(i,vm,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=Yt(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=nd(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=oe(u.definition?.id??e);await sv(s,i,r,a,p),await It({pmRoot:i,filePath:o,raw:Xt(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:T()}}function Sm(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 uv(e,t,n){return{...Sm(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 xm(e){return{id:e.id,source:Ma.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 Im(e,t,n){let i=e.toLowerCase();return n.has(i)?"extension":t.has(i)?"custom":"builtin"}function mv(){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 pv(e){let t=fe(e),n=[],i=[];for(let r of t.definitions){let a=xm(r);a.source==="builtin"?n.push(a):i.push(a)}return{builtin:n,custom:i}}async function ai(e){let t=M(process.cwd(),e.path);await dt(t);let n=await $(t),i=Ie(n.schema),r=Ve(t,i.files.types,$e.types),a=Co(t,i),o=H(n,F()),s=mv(),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 UD(e){let t=await ai(e),n=[],i=[],r=[];for(let s of Object.values(t.byType).sort((c,d)=>c.name.localeCompare(d.name))){let c=Im(s.name,t.customNames,new Set(t.extensionProvenance.keys())),d=Sm(s);c==="extension"?r.push(d):c==="custom"?i.push(d):n.push(d)}let a=pv(t.schema),o=Hi(t.schema).definitions.map($o);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:T()}}async function HD(e,t){let n=(e??"").trim();if(n.length===0)throw new g("Type name must not be empty.",y.USAGE);let i=await ai(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 "${Jt(n)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:uv(r,Im(r.name,i.customNames,new Set(i.extensionProvenance.keys())),i.extensionProvenance.get(r.name.toLowerCase())),file:{path:i.typesPath},generated_at:T()}}async function zD(e,t){let n=oe(e);if(n.length===0)throw new g("Status id must not be empty.",y.USAGE);let i=await ai(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 "${Jt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:xm(o),file:{path:i.statusesPath},generated_at:T()}}async function WD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{r=Kc({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 $(i),o=Ie(a.schema),s=Tr(i,o),c=[],d=Bi(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 ie(i,bm,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=Vt(p)}catch(_){throw new g(_ instanceof Error?_.message:String(_),y.GENERIC_FAILURE)}f=Yc(h,r),await It({pmRoot:i,filePath:s,raw:Kt(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:T()}}async function fv(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 qD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r=await $(i),a=Ie(r.schema),o=Tr(i,a),s=[],c=z(t.author,r.author_default),d=Me(r),l=await ie(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=Vt(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{u=Xc(f,e)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}if(u.removed){let p=oe(u.definition?.key??e),h=oe(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let _=await fv(i,r,a,h);_>0&&s.push(`items_using_field:${_}`)}await It({pmRoot:i,filePath:o,raw:Kt(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:T()}}async function GD(e){let t=await ai(e),n=Hi(t.schema).definitions.map($o);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Tr(t.pmRoot,t.schema)},generated_at:T()}}async function BD(e,t){let n=oe(e);if(n.length===0)throw new g("Field key must not be empty.",y.USAGE);let i=await ai(t),r=Hi(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 "${Jt(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:$o(r),file:{path:Tr(i.pmRoot,i.schema)},generated_at:T()}}async function JD(e,t,n){let i=M(process.cwd(),n.path);await dt(i);let r;try{let h=Vc(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${Jc.join(", ")}.`);r=h}catch(h){throw new g(h instanceof Error?h.message:String(h),y.USAGE)}let a=await $(i),o=Ie(a.schema),s=Em(i,o),c=[],d=z(t.author,a.author_default),l=Me(a),u=[],m=[],f,p=await ie(i,$r,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 Na(r)){let E=Ui(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 ri(i,Na(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:T()}}function hv(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 VD(e,t){let n=M(process.cwd(),t.path);await dt(n);let i=await $(n),r=Ie(i.schema),a=Em(n,r),o=hv(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=nm(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:T()}}let h=z(e.author,i.author_default),_=Me(i),w=await ie(n,$r,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=La({name:I.name})}catch{f.push({name:I.name,reason:"invalid_type_token"});continue}let S=Ui(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 ri(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:T()}}import Rm from"node:fs/promises";import To 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 Dr(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 Do(e){return Hc(e)}async function _v(e){try{let t=JSON.parse(await Rm.readFile(To.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 gv(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 _v(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 wn(e,t={}){let n=To.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 Rm.readFile(n,"utf8"))}catch(o){throw new g(`Failed to parse extension manifest at "${n}": ${yv(o)}`,y.USAGE)}let r=Do(i);if(!r)throw new g(`Extension manifest at "${n}" is invalid.`,y.USAGE);let a=To.resolve(e,r.entry);if(!ue(e,a))throw new g(`Extension entry "${r.entry}" resolves outside extension directory "${e}".`,y.USAGE);if(!await D(a))throw await gv(r,a,t);if(!await zc(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 yv(e){return e instanceof Error?e.message:String(e)}import Oo from"node:fs/promises";import wv 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 vv=".managed-extensions.json",Or=1;function oi(e){return wv.join(e,vv)}function bv(){return{version:Or,updated_at:T(),entries:[]}}function si(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 Am(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 kv(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 Ev(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 Sv(e){if(typeof e!="object"||e===null)return null;let t=e;if(!kv(t))return null;let n=Ev(t.source);if(!n)return null;let i=Fc(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 xv(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Or||!Array.isArray(t.entries))return null;let n=[];for(let i of t.entries){let r=Sv(i);r&&n.push(r)}return{version:Or,updated_at:ve(t.updated_at)??T(),entries:si(n)}}async function he(e){let t=oi(e),n=bv();try{let i=await Oo.readFile(t,"utf8"),r=JSON.parse(i),a=xv(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 vn(e,t){let n=oi(e),i={version:Or,updated_at:T(),entries:si(t.entries)};await Oo.mkdir(e,{recursive:!0}),await Oo.writeFile(n,`${JSON.stringify(i,null,2)}
|
|
29
29
|
`,"utf8")}function ci(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:T(),entries:si(n)}}async function Cm(e,t,n,i){let r=t.entries.find(o=>R(o.name)===R(n));if(!r)return t;let a=ci(t,{...r,contributions:i});return await vn(e,a),a}import{execFile as Nv}from"node:child_process";import J from"node:fs/promises";import Fo from"node:os";import N from"node:path";import{fileURLToPath as Mv}from"node:url";import{promisify as jv}from"node:util";import Fv from"npm-package-arg";import{extract as Uv,list as Hv}from"tar";import Iv from"node:fs/promises";import Fe 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 Rv="PM_CLI_PACKAGE_ROOT",$m={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Av=new Set(["*","all"]);function Po(){let e=[],t=process.env[Rv];return typeof t=="string"&&t.trim().length>0&&e.push(Fe.resolve(t.trim())),e.push(qe(import.meta.url,["../../.."])),[...new Set(e)]}async function di(e){let t=e.trim().toLowerCase(),n=await Dm(t);if(n)return n;let i=$m[t];if(!i)return null;for(let r of Po()){let a=Fe.join(r,".agents","pm","extensions",i.legacy_extension_directory);if(await D(Fe.join(a,"manifest.json")))return a}return null}function Tm(e){return Av.has(e.trim().toLowerCase())}function Cv(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function $v(e,t){let n=await Iv.readdir(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!i.name.startsWith("pm-"))continue;let r=Fe.join(e,i.name);if(!await D(Fe.join(r,"package.json")))continue;let a=await ji(r),o=a.aliases&&a.aliases.length>0?a.aliases:[Cv(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 Lo(){let e=new Map;for(let t of Po()){let n=Fe.join(t,"packages");await D(n)&&await $v(n,e)}for(let[t,n]of Object.entries($m))if(!e.has(t))for(let i of Po()){let r=Fe.join(i,"packages",n.package_directory);if(await D(Fe.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 Pr(){return(await Lo()).map(e=>e.alias)}async function Dm(e){let t=e.trim().toLowerCase();return(await Lo()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function Om(e){let t=await Dm(e);return t?(await ji(t)).package_name??null:null}async function Pm(e){let t=await di(e);if(!t)return null;try{let n=await Fi(t);return n.length!==1?null:(await wn(n[0])).manifest.name}catch{return null}}function Tv(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 Dv(e,t,n,i,r,a){let o=i==="global"?"--global":"--project",s=Object.fromEntries(Pa.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(Fe.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:Tv(e),media:e.catalog?.media}}}async function Lm(e,t,n={}){let i=Bt(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=>Fe.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 Lo()){let f=Fe.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 ji(f.package_root);c.push(Dv(h,f,p,e,s,o))}let l=Pv(n.fields),u=l?c.map(m=>Lv(m,l)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Pa.filter(m=>m!=="extensions"),packages:u}}var Ov=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 Pv(e){if(e===void 0)return;let t=wl(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=>!Ov.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 Lv(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 Mm=jv(Nv),Nr="@unbrained/pm-cli",zv={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},No;async function jm(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 Mo(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 Wv(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 li(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 Wv(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 Mo(s,n,i)}catch{return null}})();if(r)return r;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=Mo(a,n,i);if(!o)throw new g(`Invalid GitHub source "${n}".`,y.USAGE);return o}if(t.forceGithub){let o=Mo(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 Lr(e,t=Mm,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(" ")}
|
|
@@ -49,10 +49,10 @@ ${d}`,y.GENERIC_FAILURE)}}function Um(e){let t=e.trim(),n=t.includes("@file:")?t
|
|
|
49
49
|
`,conflict_paths:c,paths_from_theirs:d,preferred:r}}import Kr from"node:path";import{execFile as fS}from"node:child_process";import{createHash as Ef}from"node:crypto";import{readdir as hS}from"node:fs/promises";import _S from"node:path";import{promisify as gS}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=gS(fS),Vr=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function nM(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 qn(o.trim(),128))?.trim();if(s===void 0||!Vr.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||!Vr.test(o))return;let{stdout:c}=await ut("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Ef(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 Sf(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"&&Vr.test(t.original_head)&&typeof t.original_blob=="string"&&Vr.test(t.original_blob)}async function xf(e,t,n,i){if(i!==void 0&&Ef(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 hS(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","--",_S.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 yS=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,wS=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Xr=2048,vS=64,bS=1e5,kS=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 yS.test(e)}var ES=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),Zr="bounded_non_sensitive_scalars_v1",SS=new Set(["open","in_progress","blocked","closed","canceled"]),xS=new Set(["risk","confidence","severity"]),IS=new Set(["low","medium","high","critical"]),Rf=new Map([["priority",new Set([0,1,2,3,4].map(A))],["status",new Set([...SS].map(A))],...[...xS].map(e=>[e,new Set([...IS].map(A))])]);function Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Af(e,t){return Object.keys(e).every(n=>t.has(n))}function Yr(e){return Array.isArray(e)&&e.length<=Xr&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function yi(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let i=t.pop();if(n+=1,n>bS||i.depth>vS)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 Cf(e){if(!Qe(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[Af(e,ES),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"),yi(e.base),yi(e.ours),yi(e.theirs),yi(e.retained),yi(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function RS(e){if(!Qe(e))return!1;let t=Object.entries(e);return t.length<=Xr&&t.every(([n,i])=>n.length>0&&n.length<=256&&typeof i=="string"&&/^[a-f0-9]{64}$/u.test(i))}function AS(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||Kr.posix.isAbsolute(e))return!1;let n=Kr.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&Kr.posix.basename(n,Kr.posix.extname(n))===t}function CS(e){return!Yr(e.fields_from_theirs)||!Yr(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Xr||!e.decisions.every(Cf)?!1:e.merged_field_hashes===void 0||RS(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===Zr)&&r.includes(e.evidence_source)}function TS(e){return typeof e.created_at=="string"&&Zt(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Zt(e.reconciled_at))}function If(e,t){if(!Qe(t)||ta(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||Rf.get(e)?.has(A(i))===!0)&&At(i)===t.pm_value_hash}function DS(e){if(!e.decisions.every(i=>i.base===null&&i.ours===null&&i.theirs===null&&If(i.field,i.retained)&&If(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===Zr)}function OS(e){return e.operation!==void 0&&!Sf(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function PS(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||!Af(e,kS)?"required_fields":typeof e.id!="string"||!mt(e.id)?"receipt_id":typeof e.item_id!="string"||!wS.test(e.item_id)?"item_id":AS(e.item_path,e.item_id)?null:"item_path"}function Qr(e,t){if(!Qe(e))return"required_fields";let n=PS(e);return n!==null?n:OS(e)?CS(e)?$S(e)?TS(e)?t==="durable"&&!DS(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function ea(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(!Yr(e.fields_from_theirs))return"fields_from_theirs";if(!Yr(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>Xr)return"decisions";let t=e.decisions.findIndex(n=>!Cf(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function us(e,t){return Qr(e,t)===null}function ta(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 ms(e,t){let n=Sn(t),i=At(n?void 0:t);return!n&&(t===null||Rf.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]="21c15a9e-da38-5fec-9a7d-57556f77ce0a")}catch{}})();var US=FS(LS),ps=16*1024*1024,na=100;async function fs(e){try{let{stdout:t}=await US("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 Of(e,t){let n=me.dirname(me.resolve(e,t));for(let i=0;i<12;i+=1){if(await D(me.join(n,"settings.json")))return n;let r=me.dirname(n);if(r===n)break;n=r}return null}function ia(e){return me.join(e,"merge-receipts")}function Ct(e){return`${e}.json`}async function Tf(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await qn(e.receiptPath,ps)}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=ea(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!us(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||me.basename(e.receiptPath)!==Ct(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:vi(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
50
|
`}}function wi(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)))})):ra(e).decisions}))}function vi(e){let t=[wi(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(wi(e,!0)),t}function HS(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 zS(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 nt(me.join(n,"history",`${a.item_id}.jsonl`),a.item_id),bt(o).ok||(o=[])}catch{o=[]}i.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=A({...ra(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 ra(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:ta(t.retained)??At(Sn(t.retained)?void 0:t.retained),discarded_hash:ta(t.discarded)??At(Sn(t.discarded)?void 0:t.discarded)}))}}async function IM(e){let t=await fs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,r=me.basename(i,me.extname(i)),a={version:1,id:NS(),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:T(),value_availability:"clone_local"};await Ln(t),await Z(me.join(t,Ct(a.id)),`${JSON.stringify(a,null,2)}
|
|
51
51
|
`);let o=await Of(e.cwd,a.item_path);if(o!==null){let s=ia(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:ms(u.field,u.retained),discarded:ms(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:Zr};await Ln(s),await Z(me.join(s,Ct(a.id)),`${JSON.stringify(l,null,2)}
|
|
52
|
-
`)}return a}async function Df(e,t){let n;try{n=await MS(e)}catch(s){let c=await WS(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>=na)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 qS(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 WS(e,t,n=jS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=me.dirname(i);if(a===i)return!0;i=a}}async function qS(e,t,n){let i;try{i=await qn(me.join(e,t),ps)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=ea(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=Qr(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!==Ct(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 GS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-YCLN2ZZG.js"),r=await i(e,ia(t),n.map(a=>Ct(a.id)),ps);return n.flatMap(a=>{try{let o=ea(JSON.parse(r.get(Ct(a.id))??""));if(Qr(o,"durable")!==null)return[];let s=o,c=vi(a);return s.id===a.id&&vi(s).some(d=>c.includes(d))?[a.id]:[]}catch{return[]}})}async function pt(e,t={}){let n=await fs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Df(n,"clone_local"),r=t.pmRoot??me.join(e,".agents","pm"),a=await Df(ia(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?vi(u):[wi(u)]).includes(wi(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<na&&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:HS(u,m))}await zS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await GS(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,na),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>na,clone_local_evidence_resolved:n!==null}}function Pf(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 xn(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 RM(e,t,n={}){let i=await fs(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(!us(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=T(),o=me.join(i,Ct(t.id)),s=await Of(e,t.item_path),c=s===null?null:me.join(ia(s),Ct(t.id)),d=(await Promise.all([Tf({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Tf({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)?[wi(t)]:vi(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 AM(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:T()}}import{createHash as BS}from"node:crypto";import aa 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 JS="2026-08-09T16:15:18.000Z",Nf=Symbol("pre-durable-disposition-eligible");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hs(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 Lf(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 Mf(e,t){if(typeof e!="string")return!1;let n=aa.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!aa.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(aa.posix.basename(n)===`${t}.toon`||aa.posix.basename(n)===`${t}.md`)}function VS(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&&Mf(e.item_path,t)}function jf(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=>Lf(o)?[o.field]:[])):new Set;return hs(t)&&hs(n)&&hs(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Lf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function KS(e,t){return VS(e,t)&&jf(e)}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==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Mf(e.item_path,t)&&jf(e)}function XS(e){return e[Nf]===!0}function Ff(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:KS(i,t),[Nf]:YS(i,t),...typeof e.ts=="string"&&Zt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Uf(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"||!Zt(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 Hf(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=>XS(a)&&a.eventTimestamp!==void 0&&Pt(a.eventTimestamp,JS)<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:BS("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as ZS}from"node:buffer";import{readFile as QS}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 e0(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 t0(e){if(Te(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(`
|
|
52
|
+
`)}return a}async function Df(e,t){let n;try{n=await MS(e)}catch(s){let c=await WS(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>=na)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 qS(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 WS(e,t,n=jS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=me.dirname(i);if(a===i)return!0;i=a}}async function qS(e,t,n){let i;try{i=await qn(me.join(e,t),ps)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=ea(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=Qr(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!==Ct(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 GS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-YFDNGHCM.js"),r=await i(e,ia(t),n.map(a=>Ct(a.id)),ps);return n.flatMap(a=>{try{let o=ea(JSON.parse(r.get(Ct(a.id))??""));if(Qr(o,"durable")!==null)return[];let s=o,c=vi(a);return s.id===a.id&&vi(s).some(d=>c.includes(d))?[a.id]:[]}catch{return[]}})}async function pt(e,t={}){let n=await fs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Df(n,"clone_local"),r=t.pmRoot??me.join(e,".agents","pm"),a=await Df(ia(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?vi(u):[wi(u)]).includes(wi(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<na&&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:HS(u,m))}await zS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await GS(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,na),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>na,clone_local_evidence_resolved:n!==null}}function Pf(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 xn(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 RM(e,t,n={}){let i=await fs(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(!us(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=T(),o=me.join(i,Ct(t.id)),s=await Of(e,t.item_path),c=s===null?null:me.join(ia(s),Ct(t.id)),d=(await Promise.all([Tf({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Tf({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)?[wi(t)]:vi(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 AM(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:T()}}import{createHash as BS}from"node:crypto";import aa 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 JS="2026-08-09T16:15:18.000Z",Nf=Symbol("pre-durable-disposition-eligible");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hs(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 Lf(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 Mf(e,t){if(typeof e!="string")return!1;let n=aa.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!aa.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(aa.posix.basename(n)===`${t}.toon`||aa.posix.basename(n)===`${t}.md`)}function VS(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&&Mf(e.item_path,t)}function jf(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=>Lf(o)?[o.field]:[])):new Set;return hs(t)&&hs(n)&&hs(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Lf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function KS(e,t){return VS(e,t)&&jf(e)}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==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Mf(e.item_path,t)&&jf(e)}function XS(e){return e[Nf]===!0}function Ff(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:KS(i,t),[Nf]:YS(i,t),...typeof e.ts=="string"&&Zt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Uf(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"||!Zt(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 Hf(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=>XS(a)&&a.eventTimestamp!==void 0&&Pt(a.eventTimestamp,JS)<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:BS("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as ZS}from"node:buffer";import{readFile as QS}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 e0(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 t0(e){if(Te(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
53
|
`).entries()){if(!s.trim()){n+=s.length+1;continue}let c=e0(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=bt(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 n0(e,t,n){if(!e.located)return{itemRaw:null,document:n};let i=await rl(e.located,{schema:t.schema});return{itemRaw:i.raw,document:i.document??n}}async function zf(e){let t;try{t=await QS(e)}catch(n){if(j(n))return null;throw n}if(!ZS(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 Wf(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=t0(a),s=Yd(o.entries,o.entries.length-1),c=Hd(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 n0(t,n,c),l=uo({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 ie(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=er({...Ud({hashAlgorithm:Re(o.entries.at(-1).hash_algorithm),nowIso:T(),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 Er({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:T()}}import{realpath as Vf}from"node:fs/promises";import _s from"node:path";import Kf 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 qf(e,t){return t==="body"?e.body:e.metadata[t]}function i0(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 r0(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 Gf(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(i=>i0(e,i)))return t;let n=t.map(i=>e==="comments"?i:r0(i));return[...new Map(n.map(i=>[A(i),i])).values()]}function gs(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)&&gs(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)&&gs(r,n[i]))}function Bf(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 ir(a.patch))o.add(ar(c.path)),c.from&&o.add(ar(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 a0(e,t,n){let i=Kf.compare(t,n);if(i.length===0)return;let r=new Set;for(let p of i)r.add(ar(p.path));let a=new Set([...r].filter(p=>gs(Gf(p,qf(t,p)),Gf(p,qf(n,p))))),o=new Set([...r].filter(p=>!a.has(p))),s=Bf(e,o),c=Bf(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 o0(e){try{return await Vf(e)}catch{return null}}async function s0(e){if(await o0(_s.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 c0(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 Vf(e.itemPath),i=[];for(let o of t){let s=await s0({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 Jf(e,t,n,i){if(e===void 0)return;let{receipt:r,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:_s.relative(a,t.currentItemPath).split(_s.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 xf(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 d0(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))??[];Pf(t,n,e.options.dryRun===!0);let r=e.options.mergeReceiptProof?await c0({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(ra)}}:e.options.auditContext}}function l0(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=nr(r.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:en(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:r.raw,loadedItem:r}}function u0(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 m0(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=en(e.finalReplay,e.itemHashVersion,i),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(a),s=en(n,e.itemHashVersion,i),c={hash_algorithm:i,ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Kf.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(er({...c,event_class:Ld(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function p0(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 ys(e,t,n){let{pmRoot:i,settings:r,typeRegistry:a}=await Ka(n.path),o=await Il(i,e,r,a.type_to_folder);return t.salvageTail===!0?Wf({pmRoot:i,subject:o,settings:r,typeRegistry:a,options:t,author:z(t.author,r.author_default)}):Ru({pmRoot:i,subject:o,settings:r,typeRegistry:a,operation:"history-repair",options:t,transform:s=>h0({pmRoot:i,subject:o,options:t},s)})}function f0(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 h0(e,t){let{pmRoot:n,subject:i,options:r}=e,a=t.entries,o=t.verification,s=bt(a),c=r.normalizeProvenance?bu(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=zd(c.entries),l=new Set(c.entries.map(P=>P.item_hash_version).filter(P=>P!==void 0)),u=rr(c.entries,d),m=l0(i,t,d);await Jf(r.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=en(f,d),h=!1;if(m.currentItemReplay!==null){let P=en(m.currentItemReplay,d);h=!p.some((x,q)=>x===P[q])}let _=h&&m.currentItemReplay?a0(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await d0({options:r,pmRoot:n,subjectId:i.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,f0(r,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,I=!!r.dryRun,C=u0({message:r.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=m0({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=p0(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>Jf(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:T()})}}function bj(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 kj(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 Ka(t.path),a=[],o=await rt(n,i.item_format,r.type_to_folder,a,i.schema,{forceSourceScan:!0}),s=await Ft(n,o),c=e.normalizeProvenance?await ku(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 ys(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 Nd(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:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="11486e17-e6da-5770-8621-f59a17bb4922")}catch{}})();var _0=new Set(gl),Yf=25,g0=be.join("runtime","telemetry","events.jsonl"),y0=be.join("runtime","telemetry","state.json"),w0=2500,v0=500,Xf=bl-3,b0=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Ss(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 xs(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function In(e){return e.trim().toLowerCase()}function bs(e,t){let n=In(e),i=In(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Is(e){try{return(await ht.stat(e)).isDirectory()}catch{return!1}}async function k0(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=>Nn.some(a=>r.name.endsWith(a))).map(r=>be.parse(r.name).name)))}async function E0(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 S0(e,t,n){let i=be.join(e,"history");if(!await Is(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 E0(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 ks(e,t){return be.relative(e,t).replaceAll("\\","/")}async function Zf(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)Nn.some(c=>s.toLowerCase().endsWith(c))&&i.push(be.join(a,s))}return i.sort((r,a)=>ks(e,r).localeCompare(ks(e,a))),i}function x0(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function I0(e,t,n){let i=await Zf(e,t),r=[],a=[],o=[],s=[],c=qt(F());for(let d of i){let l=ks(e,d),u;try{u=await ht.readFile(d,"utf8")}catch{r.push(l);continue}let m=Te(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:Yi(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function R0(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){x0(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=Te(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(...Ff(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Uf(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 Qf(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 A0(e,t,n,i,r,a){let o=await I0(e,t,n),s=await R0(e),c=Xi(o.formatVersions,Fn,Ki),d=fe(n),l=pr(a,x=>Td(x,d),Wn()),u=await Br(e),m=await Et(e),f=await lf(e,m),p=await uf(e,m,i,r),h=m===null?null:await cn(m),_=await pt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(_.durable_receipt_ids),v=Hf(s.mergeReceiptReferences,w,s.mergeReceiptDispositions),E=v.missing,k=_.receipts.filter(x=>x.state==="pending"),{pendingDecisions:I,lossless:C}=xn(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}`),...Qf(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}`]:[],...mf({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,Cu)},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,mo),missing_merge_receipt_history_reference_details_truncated:E.length>mo}},warnings:O,gitWorkspaceRoot:m,pendingMergeReceipts:k}}function C0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function $0(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:C0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function T0(e,t){return Y(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function D0(e){let t=Y(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function O0(e){return Y(e.reason)??Y(e.error)??Y(e.message)}function ws(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 P0(e){let t=[],n=[],i=[];e.forEach((a,o)=>{let s=T0(a.definition,o),c=D0(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:O0(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(ws),n.sort(ws),i.sort(ws);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 eh(e,t,n,i,r,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>xs(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=d.map(ni).filter(_=>_!==void 0),h=Go(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: ${Oi.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 L0(e,t,n){let i=await Zo(Ge(e)),r=await Be({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(S=>$0(S)),o=await wu(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 Xo(e,s.registrations.migrations);let l=P0(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=>In(S.name))),f=new Set(d.state.entries.map(S=>In(S.name))),p=[...new Map(r.loaded.filter(S=>!(S.layer==="project"?m:f).has(In(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=>bs(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!bs(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=pi(E),I=fi(),C=eh(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 Es(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=$u(e,Yf);return{values:n.values,truncated:n.truncated,total:e.length}}function oa(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function N0(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return _0.has(e)?e:null}function sa(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 th(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>=Xf&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:a}}function M0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function j0(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 F0(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Ja().telemetry_disabled?void 0:{attempted:!0,...await nh(n)}}function U0(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>=v0;return(o||s||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function H0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function z0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>vl?[`telemetry_schema_version_behind:${t}`]:[]}function W0(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 q0(){return{...Ja(),pm_no_telemetry:oa("PM_NO_TELEMETRY"),telemetry_otel_disabled:oa("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:oa("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:N0()}}function G0(e,t){return e.telemetry.enabled&&t.validEntries>0}function B0(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function nh(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(w0)});return{probe_url:sa(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of b0){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:sa(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function J0(e,t){let n=Ni(process.cwd()),i=be.join(n,g0),r=be.join(n,y0),a=await B(i),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?th(a):M0(),d=await B(r),{runtimeState:l,stateParseFailed:u}=j0(d),m=e.telemetry.endpoint.trim(),f=sa(m),p=await F0(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...U0(e,c,l),...H0(p),...z0(p),...W0(e,l));let _=G0(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:B0(_,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:Xf,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:q0()}},warnings:h}}async function V0(e){let t;try{t=await Zu(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 K0(e){let t="metadata",n=e.items,i=await Ft(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 Ft(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 Y0(e,t){let n=dr(e),i=zn(n.settings),r=mr(n.settings,t),a=i.active?Nt(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(i.active&&r.active)}}function X0(){return{refreshed:[],skipped:[],warnings:[]}}async function Z0(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?X0():_l(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Q0(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&rn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function ex(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 tx(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function ih(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:qa(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:qa(i,e.vector_store?.adapter??null)}}function nx(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function ix(e,t,n){return e.enabled&&n.length>0&&t}async function rx(e,t,n,i,r){let a=Y0(t,e),o=await an(e),s=a.semanticRuntimeAvailable?Ya(n,o.entries):[],c=await Z0({pmRoot:e,snapshot:a,refreshPolicy:i,staleBefore:s}),d=await an(e),l=a.semanticRuntimeAvailable?Ya(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=Q0({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=ex({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Es(s,r),h=Es(l,r),_=ix(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:nx(i),...ih(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:Yf,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:tx(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 ax(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 rh(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 ox=new Set(["extensions","locks","search"]);function sx(e){let t=new Set(vc.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(bc));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of ox)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 cx(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:a}=sx(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 Is(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 ah(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 dx(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 vs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function lx(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 ux(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 mx(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 Rs=e=>e.unknown_event_count??0,As=e=>e.actionable_unknown_event_count??Rs(e);function px(e,t,n,i,r,a){let o=Rs(i),s=As(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 oh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function fx(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 hx(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function _x(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 sh(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=vo(i)?.code??xs(i),o=n.get(r)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=ni(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=Ss(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 gx(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 yx(e){for(let t of e.checks){let n=bo(e.remediationSources[t.name]);gx({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function wx(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 ys(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 vx(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 ch(e,t={}){let n=M(process.cwd(),e.path);await te(n);let i=Gt(n),{settings:r,warnings:a}=await Jd(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=rh(t),m=await cx(n,s,c),f=ax(r),p=await J0(r,{checkTelemetry:t.checkTelemetry===!0}),h=await L0(n,r,!!e.noExtensions),_=ah(t),w=[],v=await dx({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Sr(fe(r.schema),v),I=[...(await Uu({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(le=>le.startsWith("agent_guidance_")),...f,...xr(k)],C=_.skipDrift?{warnings:[]}:await Wd({pmRoot:n,settings:r,itemIds:v.map(le=>le.id),commandLabel:"health"}),S=await S0(n,r.history.compact_policy,await k0(n)),b=await Xn(n,20,t.verboseAuthorEvents===!0),O=As(b),P=O>0?[`history_unknown_author_events:${O}`]:[],x=oh(await yl(n,v,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),q=await xu(n),Se=q.warnings,_e=await V0(n),pe=_.skipIntegrity&&!l?{...vs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await A0(n,s.type_to_folder,r.schema,r,l,v),Le=_.skipDrift?vs("history_drift"):await K0({pmRoot:n,items:E,settings:r,typeRegistry:s,itemReadWarnings:w}),$i=[...new Set(w)],Pn=await wx({gitWorkspaceRoot:pe.gitWorkspaceRoot,pendingMergeReceipts:pe.pendingMergeReceipts,historyDriftCheck:Le,global:e});vx(Le,Pn);let U=_.skipVectors?vs("vectorization"):await rx(n,r,E,u,t.verboseStaleItems===!0),G=[lx(i,r,o),ux(m,c),mx(I,k),p.check,h.check,px(v,r,S,b,x.scan,q),_e.check,pe.check,Le.check,U.check],Ti=fx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:$i,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U}),Di=_x({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:$i,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U});yx({checks:G,remediationSources:Di,historyDriftedCount:hx(Le),overThresholdCount:S.over_threshold.length});let Ia=Ti.filter(le=>!Ss(le,l)),Ra=sh({warnings:Ti,checks:G,remediationSources:Di,requireMergeDrivers:l}),rg=new Set(Ra.filter(le=>le.severity==="gate_failing").map(le=>le.check)),ag=new Set(Ra.map(le=>le.check));for(let le of G)le.ok=!rg.has(le.name),ag.has(le.name)&&(le.status="warn");let og={ok:Ia.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Ia.length>0?y.GENERIC_FAILURE:0},checks:G,warnings:Ti,findings:Ra,failed_because:Ia,generated_at:T()};return ho(og,t,_.summaryMode)}var k1={buildHierarchyIntegrityWarnings:Qf,buildExtensionHealthTriageSummary:eh,buildHealthFindings:sh,buildCapabilityContractMetadata:fi,buildStaleInProgressHealthSummary:oh,buildVectorizationProviderDetails:ih,collectUnknownCapabilityGuidance:pi,isAdvisoryHealthWarning:Ss,isDirectory:Is,isExpectedUnmanagedExtension:bs,listItemDocumentPaths:Zf,normalizeEndpointForDisplay:sa,normalizeExtensionNameForMatch:In,parseTelemetryQueue:th,probeTelemetryEndpointHealth:nh,projectHealthResult:ho,resolveActionableUnknownAuthorEventCount:As,resolveHealthSkipPolicy:ah,resolveUnknownAuthorEventCount:Rs,resolveVectorRefreshPolicy:rh,selectStaleItemDetail:Es,summarizeHealthCheckDetails:po,summarizeExtensionList:Qn,summarizeRecordList:je,summarizeStringList:W,telemetryEnvFlagEnabled:oa,warningCode:xs};(function(){try{var e=typeof window<"u"?window:typeof 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 dh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Rl(e,t).ok)return{reason:"unverified_history"};let i=tr(),r={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(i.metadata.status));i=Kd(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 lh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function uh(e,t,n,i,r){let a=lh(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(Dt(e,d.id),d.id),{body:m,...f}=d;l=dh(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 mh(e,t){let n=M(process.cwd(),t.path),i=await $(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(Dt(n,a.metadata.id),a.metadata.id),s=lh(r),c=dh(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 bx(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function ph(e){return`${e.item_id} ${e.link_kind}`}function fh(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=bx(r.classification,i.classification),r.owners.set(ph(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[ph(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 hh(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=fh(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=Zi(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 Rn from"node:fs/promises";import An 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 kx(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let a;try{a=await Rn.readdir(An.join(e,r))}catch{return}for(let o of a)for(let s of Nn)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 Ex(e,t){let{id:n,relativePath:i,liveItemIds:r,out:a}=e,o=Te(t);if(o){a.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=Sx(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 Sx(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 Cs(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 xx(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await Rn.readdir(An.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 Rn.readFile(An.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Cs("history stream",o)});continue}Ex({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},a)}return n}function _h(e){let t=Te(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 Ix(e){let t=[],n=0,i=null;try{i=await B(Gt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Cs("configuration file",a)})}if(i!==null){n+=1;let a=_h(i);a!==null&&t.push({path:"settings.json",detail:a})}let r;try{r=await Rn.readdir(An.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 Rn.readFile(An.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Cs("configuration file",c)});continue}let s=_h(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function gh(e,t,n,i={}){let r=await kx(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=An.join(e,u.relativePath);return vt(await Rn.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 xx(e,a),l=await Ix(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 tc from"node:fs/promises";import{realpathSync as FI}from"node:fs";import{execFile as UI}from"node:child_process";import Ee from"node:path";import{promisify as HI}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 Rx=["metadata","resolution"],$s=["metadata","resolution","estimates","timestamps","lifecycle"],Ax="completed";function Ts(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function yh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function wh(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=yh(n.close_reason)??Ax;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${Ts(i)}`,gate:"resolution"})}return t}function vh(e){let t=[];for(let n of e){let i=yh(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 ${Ts(i)}`,gate:"metadata"})}return t}function bh(e,t){return e.map(n=>{let i=Gd(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 kh(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 Eh(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 ${Ts(n.path)}`})}return t}function Sh(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(Rx)}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 xh(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 bi(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 Cx=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function $x(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=Cx.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 Ih(e){return typeof e=="string"&&e.trim().length>0}function Tx(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 Rh(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||Ih(r.duplicate_of))continue;let a=$x(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:Ih(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=Tx(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 Ah(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 Ch(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=Ch(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(Ch(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 Th(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 Dx=/^[a-z][a-z0-9+.-]+:\/\//i;function ki(e){return Dx.test(e.trim())}import Ox from"node:fs/promises";import ke from"node:path";import{glob as Px}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 Lx=["path","scope","note"],Nx=["pattern","glob","path","scope","note"],Mx=["path"],jx=["from","to"],Fx=new Set(["note","scope"]);function Oh(e){let t=e??"project";if(!Aa.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Aa.join(", ")} (default: project).`,y.USAGE);return t}function Ds(e){if(e.startsWith("```")||e.includes(`
|
|
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:T()}}import{realpath as Vf}from"node:fs/promises";import _s from"node:path";import Kf 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 qf(e,t){return t==="body"?e.body:e.metadata[t]}function i0(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 r0(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 Gf(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(i=>i0(e,i)))return t;let n=t.map(i=>e==="comments"?i:r0(i));return[...new Map(n.map(i=>[A(i),i])).values()]}function gs(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)&&gs(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)&&gs(r,n[i]))}function Bf(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 ir(a.patch))o.add(ar(c.path)),c.from&&o.add(ar(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 a0(e,t,n){let i=Kf.compare(t,n);if(i.length===0)return;let r=new Set;for(let p of i)r.add(ar(p.path));let a=new Set([...r].filter(p=>gs(Gf(p,qf(t,p)),Gf(p,qf(n,p))))),o=new Set([...r].filter(p=>!a.has(p))),s=Bf(e,o),c=Bf(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 o0(e){try{return await Vf(e)}catch{return null}}async function s0(e){if(await o0(_s.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 c0(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 Vf(e.itemPath),i=[];for(let o of t){let s=await s0({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 Jf(e,t,n,i){if(e===void 0)return;let{receipt:r,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:_s.relative(a,t.currentItemPath).split(_s.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 xf(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 d0(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))??[];Pf(t,n,e.options.dryRun===!0);let r=e.options.mergeReceiptProof?await c0({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(ra)}}:e.options.auditContext}}function l0(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=nr(r.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:en(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:r.raw,loadedItem:r}}function u0(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 m0(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=en(e.finalReplay,e.itemHashVersion,i),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(a),s=en(n,e.itemHashVersion,i),c={hash_algorithm:i,ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Kf.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(er({...c,event_class:Ld(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function p0(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 ys(e,t,n){let{pmRoot:i,settings:r,typeRegistry:a}=await Ka(n.path),o=await Il(i,e,r,a.type_to_folder);return t.salvageTail===!0?Wf({pmRoot:i,subject:o,settings:r,typeRegistry:a,options:t,author:z(t.author,r.author_default)}):Ru({pmRoot:i,subject:o,settings:r,typeRegistry:a,operation:"history-repair",options:t,transform:s=>h0({pmRoot:i,subject:o,options:t},s)})}function f0(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 h0(e,t){let{pmRoot:n,subject:i,options:r}=e,a=t.entries,o=t.verification,s=bt(a),c=r.normalizeProvenance?bu(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=zd(c.entries),l=new Set(c.entries.map(P=>P.item_hash_version).filter(P=>P!==void 0)),u=rr(c.entries,d),m=l0(i,t,d);await Jf(r.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=en(f,d),h=!1;if(m.currentItemReplay!==null){let P=en(m.currentItemReplay,d);h=!p.some((x,q)=>x===P[q])}let _=h&&m.currentItemReplay?a0(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await d0({options:r,pmRoot:n,subjectId:i.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,f0(r,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,I=!!r.dryRun,C=u0({message:r.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=m0({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=p0(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>Jf(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:T()})}}function b1(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 k1(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 Ka(t.path),a=[],o=await rt(n,i.item_format,r.type_to_folder,a,i.schema,{forceSourceScan:!0}),s=await Ft(n,o),c=e.normalizeProvenance?await ku(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 ys(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 Nd(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:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="11486e17-e6da-5770-8621-f59a17bb4922")}catch{}})();var _0=new Set(gl),Yf=25,g0=be.join("runtime","telemetry","events.jsonl"),y0=be.join("runtime","telemetry","state.json"),w0=2500,v0=500,Xf=bl-3,b0=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Ss(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 xs(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function In(e){return e.trim().toLowerCase()}function bs(e,t){let n=In(e),i=In(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Is(e){try{return(await ht.stat(e)).isDirectory()}catch{return!1}}async function k0(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=>Nn.some(a=>r.name.endsWith(a))).map(r=>be.parse(r.name).name)))}async function E0(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 S0(e,t,n){let i=be.join(e,"history");if(!await Is(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 E0(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 ks(e,t){return be.relative(e,t).replaceAll("\\","/")}async function Zf(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)Nn.some(c=>s.toLowerCase().endsWith(c))&&i.push(be.join(a,s))}return i.sort((r,a)=>ks(e,r).localeCompare(ks(e,a))),i}function x0(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function I0(e,t,n){let i=await Zf(e,t),r=[],a=[],o=[],s=[],c=qt(F());for(let d of i){let l=ks(e,d),u;try{u=await ht.readFile(d,"utf8")}catch{r.push(l);continue}let m=Te(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:Yi(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function R0(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){x0(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=Te(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(...Ff(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Uf(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 Qf(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 A0(e,t,n,i,r,a){let o=await I0(e,t,n),s=await R0(e),c=Xi(o.formatVersions,Fn,Ki),d=fe(n),l=pr(a,x=>Td(x,d),Wn()),u=await Br(e),m=await Et(e),f=await lf(e,m),p=await uf(e,m,i,r),h=m===null?null:await cn(m),_=await pt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(_.durable_receipt_ids),v=Hf(s.mergeReceiptReferences,w,s.mergeReceiptDispositions),E=v.missing,k=_.receipts.filter(x=>x.state==="pending"),{pendingDecisions:I,lossless:C}=xn(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}`),...Qf(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}`]:[],...mf({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,Cu)},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,mo),missing_merge_receipt_history_reference_details_truncated:E.length>mo}},warnings:O,gitWorkspaceRoot:m,pendingMergeReceipts:k}}function C0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function $0(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:C0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function T0(e,t){return Y(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function D0(e){let t=Y(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function O0(e){return Y(e.reason)??Y(e.error)??Y(e.message)}function ws(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 P0(e){let t=[],n=[],i=[];e.forEach((a,o)=>{let s=T0(a.definition,o),c=D0(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:O0(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(ws),n.sort(ws),i.sort(ws);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 eh(e,t,n,i,r,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>xs(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=d.map(ni).filter(_=>_!==void 0),h=Go(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: ${Oi.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 L0(e,t,n){let i=await Zo(Ge(e)),r=await Be({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(S=>$0(S)),o=await wu(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 Xo(e,s.registrations.migrations);let l=P0(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=>In(S.name))),f=new Set(d.state.entries.map(S=>In(S.name))),p=[...new Map(r.loaded.filter(S=>!(S.layer==="project"?m:f).has(In(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=>bs(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!bs(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=pi(E),I=fi(),C=eh(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 Es(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=$u(e,Yf);return{values:n.values,truncated:n.truncated,total:e.length}}function oa(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function N0(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return _0.has(e)?e:null}function sa(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 th(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>=Xf&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:a}}function M0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function j0(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 F0(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Ja().telemetry_disabled?void 0:{attempted:!0,...await nh(n)}}function U0(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>=v0;return(o||s||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function H0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function z0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>vl?[`telemetry_schema_version_behind:${t}`]:[]}function W0(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 q0(){return{...Ja(),pm_no_telemetry:oa("PM_NO_TELEMETRY"),telemetry_otel_disabled:oa("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:oa("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:N0()}}function G0(e,t){return e.telemetry.enabled&&t.validEntries>0}function B0(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function nh(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(w0)});return{probe_url:sa(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of b0){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:sa(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function J0(e,t){let n=Ni(process.cwd()),i=be.join(n,g0),r=be.join(n,y0),a=await B(i),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?th(a):M0(),d=await B(r),{runtimeState:l,stateParseFailed:u}=j0(d),m=e.telemetry.endpoint.trim(),f=sa(m),p=await F0(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...U0(e,c,l),...H0(p),...z0(p),...W0(e,l));let _=G0(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:B0(_,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:Xf,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:q0()}},warnings:h}}async function V0(e){let t;try{t=await Zu(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 K0(e){let t="metadata",n=e.items,i=await Ft(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 Ft(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 Y0(e,t){let n=dr(e),i=zn(n.settings),r=mr(n.settings,t),a=i.active?Nt(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(i.active&&r.active)}}function X0(){return{refreshed:[],skipped:[],warnings:[]}}async function Z0(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?X0():_l(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Q0(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&rn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function ex(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 tx(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function ih(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:qa(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:qa(i,e.vector_store?.adapter??null)}}function nx(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function ix(e,t,n){return e.enabled&&n.length>0&&t}async function rx(e,t,n,i,r){let a=Y0(t,e),o=await an(e),s=a.semanticRuntimeAvailable?Ya(n,o.entries):[],c=await Z0({pmRoot:e,snapshot:a,refreshPolicy:i,staleBefore:s}),d=await an(e),l=a.semanticRuntimeAvailable?Ya(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=Q0({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=ex({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Es(s,r),h=Es(l,r),_=ix(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:nx(i),...ih(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:Yf,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:tx(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 ax(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 rh(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 ox=new Set(["extensions","locks","search"]);function sx(e){let t=new Set(vc.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(bc));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of ox)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 cx(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:a}=sx(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 Is(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 ah(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 dx(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 vs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function lx(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 ux(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 mx(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 Rs=e=>e.unknown_event_count??0,As=e=>e.actionable_unknown_event_count??Rs(e);function px(e,t,n,i,r,a){let o=Rs(i),s=As(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 oh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function fx(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 hx(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function _x(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 sh(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=vo(i)?.code??xs(i),o=n.get(r)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=ni(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=Ss(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 gx(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 yx(e){for(let t of e.checks){let n=bo(e.remediationSources[t.name]);gx({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function wx(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 ys(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 vx(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 ch(e,t={}){let n=M(process.cwd(),e.path);await te(n);let i=Gt(n),{settings:r,warnings:a}=await Jd(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=rh(t),m=await cx(n,s,c),f=ax(r),p=await J0(r,{checkTelemetry:t.checkTelemetry===!0}),h=await L0(n,r,!!e.noExtensions),_=ah(t),w=[],v=await dx({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Sr(fe(r.schema),v),I=[...(await Uu({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(le=>le.startsWith("agent_guidance_")),...f,...xr(k)],C=_.skipDrift?{warnings:[]}:await Wd({pmRoot:n,settings:r,itemIds:v.map(le=>le.id),commandLabel:"health"}),S=await S0(n,r.history.compact_policy,await k0(n)),b=await Xn(n,20,t.verboseAuthorEvents===!0),O=As(b),P=O>0?[`history_unknown_author_events:${O}`]:[],x=oh(await yl(n,v,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),q=await xu(n),Se=q.warnings,_e=await V0(n),pe=_.skipIntegrity&&!l?{...vs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await A0(n,s.type_to_folder,r.schema,r,l,v),Le=_.skipDrift?vs("history_drift"):await K0({pmRoot:n,items:E,settings:r,typeRegistry:s,itemReadWarnings:w}),$i=[...new Set(w)],Pn=await wx({gitWorkspaceRoot:pe.gitWorkspaceRoot,pendingMergeReceipts:pe.pendingMergeReceipts,historyDriftCheck:Le,global:e});vx(Le,Pn);let U=_.skipVectors?vs("vectorization"):await rx(n,r,E,u,t.verboseStaleItems===!0),G=[lx(i,r,o),ux(m,c),mx(I,k),p.check,h.check,px(v,r,S,b,x.scan,q),_e.check,pe.check,Le.check,U.check],Ti=fx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:$i,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U}),Di=_x({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:$i,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U});yx({checks:G,remediationSources:Di,historyDriftedCount:hx(Le),overThresholdCount:S.over_threshold.length});let Ia=Ti.filter(le=>!Ss(le,l)),Ra=sh({warnings:Ti,checks:G,remediationSources:Di,requireMergeDrivers:l}),rg=new Set(Ra.filter(le=>le.severity==="gate_failing").map(le=>le.check)),ag=new Set(Ra.map(le=>le.check));for(let le of G)le.ok=!rg.has(le.name),ag.has(le.name)&&(le.status="warn");let og={ok:Ia.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Ia.length>0?y.GENERIC_FAILURE:0},checks:G,warnings:Ti,findings:Ra,failed_because:Ia,generated_at:T()};return ho(og,t,_.summaryMode)}var kj={buildHierarchyIntegrityWarnings:Qf,buildExtensionHealthTriageSummary:eh,buildHealthFindings:sh,buildCapabilityContractMetadata:fi,buildStaleInProgressHealthSummary:oh,buildVectorizationProviderDetails:ih,collectUnknownCapabilityGuidance:pi,isAdvisoryHealthWarning:Ss,isDirectory:Is,isExpectedUnmanagedExtension:bs,listItemDocumentPaths:Zf,normalizeEndpointForDisplay:sa,normalizeExtensionNameForMatch:In,parseTelemetryQueue:th,probeTelemetryEndpointHealth:nh,projectHealthResult:ho,resolveActionableUnknownAuthorEventCount:As,resolveHealthSkipPolicy:ah,resolveUnknownAuthorEventCount:Rs,resolveVectorRefreshPolicy:rh,selectStaleItemDetail:Es,summarizeHealthCheckDetails:po,summarizeExtensionList:Qn,summarizeRecordList:je,summarizeStringList:W,telemetryEnvFlagEnabled:oa,warningCode:xs};(function(){try{var e=typeof window<"u"?window:typeof 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 dh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Rl(e,t).ok)return{reason:"unverified_history"};let i=tr(),r={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(i.metadata.status));i=Kd(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 lh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function uh(e,t,n,i,r){let a=lh(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(Dt(e,d.id),d.id),{body:m,...f}=d;l=dh(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 mh(e,t){let n=M(process.cwd(),t.path),i=await $(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(Dt(n,a.metadata.id),a.metadata.id),s=lh(r),c=dh(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 bx(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function ph(e){return`${e.item_id} ${e.link_kind}`}function fh(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=bx(r.classification,i.classification),r.owners.set(ph(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[ph(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 hh(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=fh(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=Zi(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 Rn from"node:fs/promises";import An 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 kx(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let a;try{a=await Rn.readdir(An.join(e,r))}catch{return}for(let o of a)for(let s of Nn)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 Ex(e,t){let{id:n,relativePath:i,liveItemIds:r,out:a}=e,o=Te(t);if(o){a.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=Sx(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 Sx(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 Cs(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 xx(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await Rn.readdir(An.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 Rn.readFile(An.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Cs("history stream",o)});continue}Ex({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},a)}return n}function _h(e){let t=Te(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 Ix(e){let t=[],n=0,i=null;try{i=await B(Gt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Cs("configuration file",a)})}if(i!==null){n+=1;let a=_h(i);a!==null&&t.push({path:"settings.json",detail:a})}let r;try{r=await Rn.readdir(An.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 Rn.readFile(An.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Cs("configuration file",c)});continue}let s=_h(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function gh(e,t,n,i={}){let r=await kx(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=An.join(e,u.relativePath);return vt(await Rn.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 xx(e,a),l=await Ix(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 tc from"node:fs/promises";import{realpathSync as FI}from"node:fs";import{execFile as UI}from"node:child_process";import Ee from"node:path";import{promisify as HI}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 Rx=["metadata","resolution"],$s=["metadata","resolution","estimates","timestamps","lifecycle"],Ax="completed";function Ts(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function yh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function wh(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=yh(n.close_reason)??Ax;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${Ts(i)}`,gate:"resolution"})}return t}function vh(e){let t=[];for(let n of e){let i=yh(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 ${Ts(i)}`,gate:"metadata"})}return t}function bh(e,t){return e.map(n=>{let i=Gd(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 kh(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 Eh(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 ${Ts(n.path)}`})}return t}function Sh(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(Rx)}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 xh(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 bi(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 Cx=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function $x(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=Cx.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 Ih(e){return typeof e=="string"&&e.trim().length>0}function Tx(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 Rh(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||Ih(r.duplicate_of))continue;let a=$x(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:Ih(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=Tx(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 Ah(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 Ch(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=Ch(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(Ch(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 Th(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 Dx=/^[a-z][a-z0-9+.-]+:\/\//i;function ki(e){return Dx.test(e.trim())}import Ox from"node:fs/promises";import ke from"node:path";import{glob as Px}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 Lx=["path","scope","note"],Nx=["pattern","glob","path","scope","note"],Mx=["path"],jx=["from","to"],Fx=new Set(["note","scope"]);function Oh(e){let t=e??"project";if(!Aa.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Aa.join(", ")} (default: project).`,y.USAGE);return t}function Ds(e){if(e.startsWith("```")||e.includes(`
|
|
56
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("=")||vd(e)}function Ux(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Hx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Ds(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&&Ux(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 zx(e,t){return e?e.flatMap(n=>{let i=n.trim();if(t==="doc"){let a=Hx(i);if(a!==void 0)return[a]}bd(i,"--add",`${t} path`,Ds(i));let r=Ds(i)?Mn(n,"--add"):{path:i};if(jn(r,"--add",Lx),!r.path)throw new g(`--add requires path=<value> or a bare ${t} path`,y.USAGE);return[{path:r.path,scope:Oh(r.scope),note:r.note?.trim()||void 0}]}):[]}function Wx(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=Mn(n,"--add-glob");jn(i,"--add-glob",Nx);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:Oh(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function qx(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=Mn(n,"--remove"),r=Object.keys(i).filter(a=>Fx.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(jn(i,"--remove",Mx),!i.path)throw new g("--remove key/value form requires path=<value>",y.USAGE);return i.path}return n}):[]}function Gx(e){return e?e.map(t=>{let n=Mn(t,"--migrate");jn(n,"--migrate",jx);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 Ei(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 Bx(e,t,n=[]){if(e.length===0||t.length===0)return;let i=new Set(e.map(a=>Ei(a.path,n))),r=[...new Set(t.map(a=>Ei(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 Os(e,t,n=process.cwd()){let i=e.trim();if(ki(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 Jx(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 Px(r.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>Os(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 Vx(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 Kx(e){return`${e.path}::${e.scope}`}function Ps(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function Ls(e){return[...new Map(e.map(t=>[Kx(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Yx(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(ki(s)){o.push(s.trim());continue}let c=ke.isAbsolute(s)?s:ke.resolve(t,s);try{(await Ox.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 Xx(e,t,n,i){let r=0;for(let a=0;a<e.length;a+=1){let o=Ei(e[a].path,i);o!==e[a].path&&(e[a]={...e[a],path:o},r+=1)}return{adds:t.map(a=>{let o=Ei(a.path,i);return o!==a.path&&(r+=1),{...a,path:o}}),removes:n.map(a=>Ei(a,i)),count:r}}function Zx(e,t,n,i){let r=Ls(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:Ps(r)}async function Dh(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 Yx(t,e.workspaceRoot):void 0}}async function ca(e,t,n,i){let{metadataKey:r}=i,a=kd(),o=M(process.cwd(),n.path),s=Ge(o),c=process.cwd();await te(o);let d=await $(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=zx(u,i.bareNoun).map(P=>({...P,path:Os(P.path,s,c)})),_=Wx(m),w=await Jx(_,s,c),v=Vx([...h,...w],t.note,h.length>0||_.length>0),E=qx(f).map(P=>Os(P,s,c)),k=Gx(p);if(Bx(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 Dh({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=Xx(Se,v,E,k),pe=Zx(Se,_e.adds,_e.removes,i.supportsAppendStable&&t.appendStable===!0);pe.length>0?x[r]=pe:delete x[r];let Le=!Dc(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 Dh({id:C.item.id,artifacts:S,changed:C.changedFields.includes(r),migrationsApplied:O,options:t,workspaceRoot:s})}function da(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 Ph(e,t,n){let i=await ca(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return da(i,"docs")}import Lh 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 Qx=32768;function Ns(e){return _t(Pe.normalize(e))}async function la(e){try{return await Lh.realpath(e)}catch{return Pe.resolve(e)}}function Cn(e,t){let n=Pe.isAbsolute(e.path)?Pe.resolve(e.path):Pe.resolve(t,e.path);return`${Ns(n)}::${e.scope}`}function ua(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)=>ua(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))ua(r,t?`${t}.${i}`:i,n)}function eI(e){let t=[];return ua(e.metadata,"metadata",t),ua(e.body,"body",t),t}function tI(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 nI(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,Qx);for(let[s,c]of[[n,r.value],[i,o]]){s.lastIndex=0;for(let d of c.matchAll(s)){let l=tI(d[0]);!l||a.has(l)||(a.add(l),t.push({field:r.field,value:l}))}}}return t}async function iI(e,t,n=t){let i=Pe.isAbsolute(e)?Pe.resolve(e):Pe.resolve(n,e),r;try{r=await Lh.stat(i)}catch{return}if(!r.isFile())return;let[a,o]=await Promise.all([la(t),la(i)]);if(ue(a,o)){let s=Pe.relative(a,o);return!s||s.startsWith("..")||Pe.isAbsolute(s)?void 0:{path:Ns(s),scope:"project"}}return{path:Ns(i),scope:"global"}}async function rI(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>Cn(c,t))),r=new Map,a=nI(eI(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await iI(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=Cn(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 Nh(e,t,n){let i=await ca(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return da(i,"files")}async function aI(e,t){let n=await la(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 la(o);return ue(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 oI(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 Mh(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function jh(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 sI(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(jh)}async function cI(e){if(e.explain)return lu({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 dI(e){if([e.strictRead,e.noTruncate,e.explain,sd()].includes(!0))return null;let t=await lr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?nl({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function lI(e){let t=[],n=await ur(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=sI({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 cI({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:jh(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:Mh(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function NF(e,t){let n=M(process.cwd(),t.path),i=Ge(n);await te(n);let r=await aI(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 $(n),o=H(a,F()),{offset:s,limit:c}=oI(e),d=await dI({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:Mh(l.item),files:l.files}))}:lI({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 MF(e,t,n){let i=M(process.cwd(),n.path),r=Ge(i);await te(i);let a=await $(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 rI(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=>Cn(Se,r)));_=[],w.clear();for(let[Se,_e]of h.entries()){let pe=Cn(_e,r);P.has(pe)||(O.push(_e),P.add(pe),_.push(_e),w.add(Se))}let x=Ls(O),q=t.appendStable?x:Ps(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=>Cn(b,r))),I=E.filter(b=>k.has(Cn(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 uI}from"node:fs";import ma 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 mI=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ms=new Set(["--pm-path","--path","--author"]),pI={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"])},fI=new Set(["-p","--package"]),hI=new Set(["-c","--call"]),_I=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),gI=new Set(["-C","--prefix","--userconfig","--cache"]),HF=new Set(["--cwd"]),zF=new Set(["--cwd"]),yI=new Set(["exec","x"]),WF=new Set(["run","run-script"]),qF=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function wI(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function vI(e,t=process.cwd()){let n=bI(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[i,...r]=n;if(Fh(i)||Uh(i,t))return r;if(i==="node"&&r[0]&&Uh(r[0],t))return r.slice(1);let a=i==="npx"||i==="bunx"?js(r):i==="pnpm"?SI(r):i==="npm"?xI(r):null;return a&&(Fh(a.command)||EI(a.command))?a.args:null}var Hh=(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 wI(a)){let c=vI(s),d=c?II(c):null,l=d&&mI.has(d.subcommand)?RI(d.remaining,pI[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 bI(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 GF(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ms.has(n)){t+=2;continue}t+=1;continue}return n}}function Fh(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function kI(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 EI(e){let t=kI(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Uh(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=ma.resolve(t,e);try{return JSON.parse(uI(ma.join(ma.dirname(ma.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function js(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(hI.has(i)){t+=1;break}t+=fI.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 SI(e){let t=zh(e,_I);return t?.subcommand!=="dlx"?null:js(t.args)}function xI(e){let t=zh(e,gI);return!t||!yI.has(t.subcommand)?null:js(t.args)}function II(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ms.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function RI(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("=")&&(Ms.has(i)||t.has(i))&&(n+=1)}}import{execFile as AI}from"node:child_process";import{readFile as CI}from"node:fs/promises";import qh from"node:path";import{promisify as $I}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 TI=$I(AI),Fs=1,DI="linked-test-trust.json";function Us(e){return qh.join(Tc(e),DI)}function Wh(){return{version:Fs,acknowledged:{}}}async function Hs(e){try{let t=JSON.parse(await CI(Us(e),"utf8"));return t.version!==Fs||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Wh():{version:Fs,acknowledged:t.acknowledged}}catch{return Wh()}}async function zs(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 TI("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 Ws(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function OI(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&ld(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function Si(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function PI(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 nU(e,t,n){if(!e||e.length===0)return e;for(let r of e)Ed(r);let i=Ws();return PI(e,t,n,await zs(i))}function Gh(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 iU(e,t,n){let i=await Hs(e);return Bh(t,n,i)}function Bh(e,t,n){let i=Gh(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||!OI(e.provenance)?a?{fingerprint:i,trusted:!0,reason:"acknowledged",...Si(void 0,t)}:{fingerprint:i,trusted:!1,reason:"invalid_provenance",...Si(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r===void 0?{fingerprint:i,trusted:!0,reason:"local_mutation",...Si(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",...Si(r,t)}:{fingerprint:i,trusted:!1,reason:"foreign_source_ref",...Si(r,t)}}async function Jh(e,t,n){let i=await Hs(e);return t.map(r=>Bh(r,n,i))}async function rU(e,t,n){let i=await Hs(e),r=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(Gh);for(let a of r)i.acknowledged[a]={acknowledged_at:n};return await Ln(qh.dirname(Us(e))),await Z(Us(e),`${JSON.stringify(i,null,2)}
|
|
57
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 pa(e){return e.includeBody?rt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):ur(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 LI=5;async function NI(e,t){let n=t.hashMismatches.filter(a=>a!==re);if(n.length===0)return;let i=await $(e),r=H(i,F());for(let a of n){let o=await ie(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 Ku(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 fa(e,t,n){let i=await Ft(e,t);await NI(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:LI,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 ha(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 MI(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function jI(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 qs(e,t=Wn()){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=MI(r.parent,n);o&&a.push(o),jI(r,i,n,t)}for(let[r,a]of i)i.set(r,[...new Set(a)].sort());return i}function Gs(e,t,n=Wn()){let i=pr(e,o=>t?Qc(o,t):o==="closed"||o==="canceled",n),r=qs(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=>ha(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 Bs(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 Js(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 zI=["src","tests","docs"],WI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],qI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),GI=["resolution","expected_result","actual_result"],BI=["default","tracked-all","tracked-all-strict"],Vh=["core","strict","custom"],ya=["off","warn","error"],Ys=["author","acceptance_criteria","estimated_minutes","close_reason"],Xh=[...Ys,"reviewer","risk","confidence","sprint","release"],Xs=Array.from(new Set(Xh)),JI={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"},VI={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"},KI={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"},YI={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"},XI={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"},ZI=32*1024*1024,QI=1e4,Zs=40,We=5,eR=4096,tR=255,nR=HI(UI);function Zh(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?Zh(i):i);return t}function iR(e){return{...e,checks:e.checks.map(t=>({...t,details:Zh(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 va(e,t){return Zi(e,t)??e}function xi(e,t){return t.terminal_statuses.has(va(e,t))}function Tt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function _a(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function rR(e){let t=Tt(kc),n={blocked_reason:Tt(Li.blocked_reason),resolution:Tt(Li.resolution),actual_result:Tt(Li.actual_result)},i=Tt(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:Tt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Tt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Tt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:_a(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:_a(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:_a(r.resolution,n.resolution)?"default":"settings",actual_result:_a(r.actual_result,n.actual_result)?"default":"settings"}}}function Qh(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Vh.includes(t))return t;throw new g(`Unknown --metadata-profile value "${e}". Supported values: ${Vh.join(", ")}.`,y.USAGE)}function e_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ya.includes(t))return t;throw new g(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ya.join(", ")}.`,y.USAGE)}function t_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ya.includes(t))return t;throw new g(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ya.join(", ")}.`,y.USAGE)}function aR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>JI[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function oR(e,t,n){let i=aR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ys],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Xh],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:[...Ys],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var sR=new Set(["acceptance_criteria","estimated_minutes"]);function n_(e,t,n,i){return!i&&sR.has(t)&&xi(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"?va(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 i_(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: ${BI.join(", ")}.`,y.USAGE)}function r_(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=Kh(n),a=Kh(i),o=Ee.relative(r,a);return o.length===0||!o.startsWith("..")&&!Ee.isAbsolute(o)?n:i}function Kh(e){try{return FI.native(e)}catch{return Ee.resolve(e)}}function cR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function nc(e,t,n){let i=t.length>0?Ee.join(e,t):e,r;try{r=await tc.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(qI.has(a.name))continue;await nc(e,o,n);continue}a.isFile()&&n.push($t(o))}}async function Qs(e){let t=[];for(let n of zI)await nc(e,n,t);for(let n of WI){let i=Ee.join(e,n);try{(await tc.stat(i)).isFile()&&t.push($t(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function a_(e){try{let{stdout:t}=await nR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:ZI,windowsHide:!0,timeout:QI}),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 dR(e,t){let n=new Set,i=Bs(wc);i.length>0&&n.add(i);let r=Bs(Ee.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((a,o)=>a.localeCompare(o))}function Yh(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function lR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await a_(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await Qs(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await Qs(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 Wt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ee(e,Zs);return{values:n.values,truncated:n.truncated,total:e.length}}var uR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},mR={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function pR(e){let t=e.missing_fields.map(n=>`${uR[n]} "${mR[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function o_(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"):em(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 s_(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 fR="validate_metadata_duplicate_issue_codes";function c_(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:[`${fR}:${e.length}`]}}function hR(e,t,n){let i=Object.fromEntries(Xs.map(r=>[r,[]]));for(let r of e)for(let a of Xs)n_(r,a,t,n)&&i[a].push(r.id);return i}function _R(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let a=t[r];a.length>0&&i.push(`${VI[r]}:${a.length}`)}return i.push(...n),i}function d_(e,t){let n={};for(let i of e.required_fields){let r=t[i],a=r?r.length:0,o=KI[i];n[o]=a}return n}function l_(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 gR(e,t,n,i){for(let r of t.required_fields){let a=n[r];if(!a||a.length===0)continue;let o=YI[r],s=XI[r];if(!o||!s)continue;let c=ee(a,i?a.length:We);e[o]=c.values,e[s]=c.truncated}}function u_(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 m_(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 yR(e,t,n,i,r){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=hR(e,n,o),c=Rh(e,{configuredPrefixes:r}),d=c_(c,i),l=_R(t,s,d.warnings),u=d_(t,s),m=l_(t,s,a),f=Ah(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:[...Xs],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]),gR(p,t,s,i);let h=u_(t,s,a),_=m_(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 wR(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(va(m.status,t))),a=[],o=[];for(let m of r){let f=GI.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=>pR(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 p_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f_(e,t="pm",n=xc()){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 __(c??"",t).filter(d=>i.has(d)).forEach(d=>o.add(d)),[a.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function h_(e,t,n){let i=El(e,n?l=>xi(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 __(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${p_(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 g_(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 y_(e,t="pm"){let n=f_(e,t),i=g_(n),r=[...new Set(i.flat())].sort((o,s)=>o.localeCompare(s)),a=i.map(o=>ha(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:a}}function w_(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 wa(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function v_(e,t){let n=wa(e).split("/").filter(Boolean),i=wa(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function vR(e,t){let n=wa(t),i=wa(e),r=t.endsWith("/")?t:`${t}/`,a=e.startsWith(r),o=n.length>0&&n===i,s=v_(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 bR(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function kR(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=vR(e,s);c!==null&&bR(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 b_(e,t){return e.map(n=>{let i=w_(n),r=i==="docs_unowned"?"docs":"files",a=kR(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 k_(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function ER(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 SR(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&&!xi(o.status,r)}}function xR(e,t,n,i){let r=ze(e.blocked_by),a=ze(e.blocked_reason),o=a?.toLowerCase(),s=va(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 IR(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=>!xi(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let d=ER(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&&xi(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(SR(c,u,r,a,n))),t){let m=xR(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 RR(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 ga(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Vs(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function AR(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=ga("validate_lifecycle_dependency_cycles",n,r.dependencyCycles),s=ga("validate_hierarchy_parent_cycle",i,r.activeHierarchyCycles),c=ga("validate_hierarchy_cardinality_violation",i,r.activeHierarchyCardinality),d=ga("validate_hierarchy_parent_divergence",i,r.activeHierarchyDivergence),l=Vs("validate_legacy_hierarchy_parent_cycle",i,r.legacyHierarchyCycles),u=Vs("validate_legacy_hierarchy_cardinality_violation",i,r.legacyHierarchyCardinality),m=Vs("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 E_(e){let t=$t(e);return t.length>eR||t.split(/[\\/]/).some(n=>n.length>tR)}async function CR(e,t){let n=Ee.isAbsolute(t)?t:Ee.resolve(e,t);if(E_(n))return!1;try{let i=await tc.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return cR(i,["ENOENT","ENOTDIR"])}}async function $R(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(ki(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=$t(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await CR(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:r.id,path:s,link_kind:o})))}return n}function TR(e,t,n,i,r,a){let o=i==="tracked-all-strict",s=o&&!r,c=r||o,d=c?[]:dR(t,n),l=d.length===0?[]:e.candidateFiles.filter(f=>Yh(f,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Yh(f,d)),m={};if(l.length>0){let f=Wt(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 S_(e,t,n,i,r,a,o,s="pm"){let c=IR(e,t,r,a);RR(c);let d=y_(c.activeItems,s),l=Gs(e,r),u=Sr(r,e,o?Number.POSITIVE_INFINITY:We),m=[...AR(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}),...xr(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 x_(e,t,n,i,r,a,o=fe(Ec.schema)){let s=await $R(e,t),c=new Map(e.map(x=>[x.id,x])),d=[...new Set(s.missingLinkedPaths)].sort((x,q)=>x.localeCompare(q)),l=await lR(t,i),u=TR(l,n,t,i,r,a),m=u.candidateFiles.filter(x=>!s.linkedProjectPaths.has(x)),f=b_(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=Wt(E,a),I=Wt(d,a),C=Wt(m,a),S=Wt(f.map(x=>`${x.path}:${x.classification}:owner_candidate=${x.owner_candidate?.id??"unowned"}`),a),b=a?f:Wt(k_(f),!1).values,O=Wt(Th(p),a),P=hh(w,p,x=>c.get(x),o,a?1/0:Zs);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:Zs,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 DR(e,t){let n=[];return e.forEach(({item:i,linkedTest:r},a)=>{let o=t[a];if(o.trusted)return;let s=Js(r.command??"");n.push(`${i.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function I_(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 zs(Ws()),u=await Jh(i,d.map(({linkedTest:I})=>I),l),m=DR(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=Hh(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}:${Js(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 OR(e,t){let n=Xi(e.map(c=>({ref:c.id,version:Yi(c)})),Fn,Ki),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:Fn,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 ec="pm validate auto-fix";async function R_(e,t,n){switch(e.kind){case"set_closed_at":await mh(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:ec};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 Ks(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function A_(e,t,n){let i=[],r=[],a=new Map;for(let o of e.filter(s=>Ks(s)===null))try{await R_(o,t,n),i.push(o)}catch(s){r.push({fix:o,error:s})}for(let o of e.filter(s=>Ks(s)!==null)){let s=Ks(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 Nh(s.item_id,{remove:c,message:ec},t):await Ph(s.item_id,{remove:c,message:ec},t),i.push(...o)}catch(d){r.push(...o.map(l=>({fix:l,error:d})))}}return{applied:i,failed:r}}var hH={applyValidateFix:R_,applyValidateFixes:A_,attachValidateFixHints:o_,buildCommandReferencesCheck:I_,buildDependencyReferencesCheck:h_,buildCloseReasonBackfillRows:u_,buildFilesCheck:x_,buildLifecycleCheck:S_,buildLifecycleDependencyGraph:f_,buildLifecycleParentGraph:qs,buildEstimateBackfillRows:m_,buildMetadataCounts:d_,buildMissingFieldOccurrences:l_,buildOrphanedPathRows:b_,classifyOrphanedPath:w_,collectDefaultProjectFileCandidates:Qs,collectTrackedGitFileCandidates:a_,detectLifecycleDependencyCycles:y_,detectLifecycleParentCycles:Gs,escapeRegExp:p_,extractItemIds:__,findLifecycleDependencyCycleComponents:g_,isMetadataFieldMissing:n_,linkedArtifactPathExceedsFilesystemLimits:E_,listFilesRecursive:nc,resolveDependencyCycleSeverity:e_,resolveParentCycleSeverity:t_,resolveFileScanMode:i_,resolveLifecycleDependencyCycleSamplePath:ha,resolveRequestedChecks:s_,resolveValidateMetadataProfile:Qh,resolveWorkspaceRoot:r_,sharedDirectoryPrefixLength:v_,summarizeOrphanedPathRows:k_,summarizeDuplicateIssueCodes:c_,toMeaningfulString:ze};function PR(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function LR(e,t,n,i){let r=await gh(e,new Set(t.map(_=>_.id)),n,{schema:i.schema,extensionFieldNames:qt(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 Br(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await sn(e,on(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 cn(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}=xn(m);f.length>0&&a.push(`validate_merge_decisions_unreviewed:${f.length}`),PR(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&&o_(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function NR(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 Yl(e.pmRoot,e.items,i?1/0:We,e.sourceIncomplete);et(t,r,n)}if(e.requestedChecks.has("metadata")){let r=yR(e.items,e.metadataPolicy,e.statusRegistry,i,[e.settings.id_prefix]);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows;let a=await uh(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=wR(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,et(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=S_(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,h_(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await x_(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 I_(e.items,e.settings.id_prefix,i,e.pmRoot),n),e.requestedChecks.has("history_drift")&&et(t,await fa(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&et(t,OR(e.items,i),n),e.requestedChecks.has("storage_integrity")&&et(t,await LR(e.pmRoot,e.items,H(e.settings,F()).type_to_folder,e.settings),n),t}function MR(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...t.closureTimestampFixes),i.push(...vh(t.closeReasonBackfillRows)),i.push(...wh(t.resolutionBackfillRows)),i.push(...bh(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...kh(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Eh(t.staleLinkPruneRows)),i}async function jR(e,t,n,i,r,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=MR(e,t,n),{applicable:s,gated:c}=xh(o,i),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await A_(s,r,a);l.push(...m.applied.map(bi)),u.push(...m.failed.map(({fix:f,error:p})=>({...bi(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(bi),applied_fixes:l,gated_fixes:c.map(m=>({...bi(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function C_(e,t,n={}){cd(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=Sh(e.fixScope),a=M(process.cwd(),t.path);await te(a);let o=await $(a),s=fe(o.schema),c=H(o,F()),d=s_(e),l=[],u=await pa({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 Xn(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=Qh(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=oR(p,f,o.validation.metadata_required_fields),_=rR(o),w=e_(e.dependencyCycleSeverity),v=t_(e.parentCycleSeverity),E=i_(e.scanMode),k=r_(a),I=await NR({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 jR(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:T(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...iR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as FR}from"node:child_process";import{promisify as UR}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 HR=UR(FR),zR=16,WR=3e4;function qR(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 GR(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 BR(e,t,n,i){let r=GR(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:r,trigger:i,pm_root:n,...od(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??WR),o.unref?.()})]);return qR(e,t.key,s)}finally{clearTimeout(o)}}function T_(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:T_(r.details,n,i,t),population_size:1,cost:e.checks.length}}async function JR(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await HR("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function VR(e,t){let n=new Array(t.length),i=0,r=Array.from({length:Math.min(zR,t.length)},async()=>{for(;i<t.length;){let a=i;i+=1;let o=t[a],s=await nt(Dt(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 Ii(e,t={}){let n=await $(e),i=H(n),r=fe(n.schema),a=(t.strict_read===!0?(await xl(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 JR(e,t.tree_id),items:a,history:t.include_history===!1?[]:await VR(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:T_(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){l??=C_({counts:!0},o);let h=await l;return $_(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=ch(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=Sd(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return BR(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as KR}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 D_(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}=Gi({...t,change:{}});return{policy:n,...i===void 0?{}:{cursor:i},...r===void 0?{}:{limit:r},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function YR(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 XR(e,t,n,i,r,a){let o=Object.fromEntries(Fa.map(f=>[f,0])),s=0,c=0,d=0,l=0,u=[],m=KR("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&&Fa.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 O_(e,t,n={}){wd(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=qi(k);I!==void 0&&a.set(k.id,I)}let o=hd(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}=XR(o,a,r,s,c,n.uncoveredOnly===!0),_=YR(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 ZR}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 ic,P_=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],rc=["measurement","assertion","gate"];function QR(e){if(P_.includes(e))return e;throw Vi({command_path:"assurance",token:e,allowed:P_,display_name:"assurance action"})}function $n(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 eA(e){if(!e)return $n("kind",`Assurance declaration kind is required. Expected: ${rc.join(", ")}`,"pm assurance list measurement");if(rc.includes(e))return e;throw new g(`Assurance declaration kind is required. Expected: ${rc.join(", ")}`,y.USAGE)}function L_(e){if(!e)return $n("preset",`Assurance preset is required. Expected: ${Zn.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(Zn.includes(e))return e;throw new g(`Assurance preset is required. Expected: ${Zn.join(", ")}`,y.USAGE)}function ac(e){return e.owner?.trim()?e.owner.trim():$n("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function tA(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 nA(e){let[t,n,i]=await Promise.all([Jn(e,"measurement"),Jn(e,"assertion"),Jn(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:i.items}}function N_(e,t){return t===!0?{id:e.id}:e}async function iA(e,t){let n=t.authorization_decision;if(!n)return[];let i=await Ii(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 rA(e,t){let n=Va(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>ln))throw new g(`assurance verdict limit must be an integer from 1 through ${ln}`,y.USAGE);let i=await Vl(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 M_(e,t,n){try{return await Xa(()=>Gl(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=de(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 aA(e,t,n){if(e==="presets"){if(t.preset??t.id)return kr(L_(t.preset??t.id),ac(t));let r=Zn.map(a=>{let o=kr(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 dn(()=>mu(n,L_(t.preset??t.id),ac(t),{author:t.author,message:t.message}));if(e==="derive"){let r=await pu(await Ii(n,{resolve_tree:!1,trigger:"derive"}),ac(t)),a=t.apply?await dn(()=>fu(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 $n("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 M_(n,"assertion",t.id);return dn(()=>hu(n,i,t.enforcement,{author:t.author,message:t.message}))}async function oA(e,t,n){if(!e.id)return $n("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(!Mt.includes(e.trigger))throw new g(`Unknown assurance trigger ${e.trigger}. Expected: ${Mt.join(", ")}`,y.USAGE);let r=e.trigger,[a,o]=await Promise.all([nA(t),Ii(t,{...n.workspace,tree_id:e.tree,trigger:r})]),s=await Xa(()=>Wl(i,a,o,{trigger:r,dry_run:e.dry_run===!0}));return s.dry_run||await Jl(t,s,{author:e.author,message:e.message}),s}function j_(e){throw e instanceof g?e:new g(e instanceof Error?e.message:"assurance risk request is invalid",y.USAGE)}function sA(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"?D_(t):Gi(t)}catch(n){if(e.action==="risk"&&n instanceof yd)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 j_(n)}}function cA(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 dA(e,t,n){let i=A(t.policy),r=ic?.pm_root===e?ic:void 0,a=new Map(n.map(d=>[d.id,ZR("sha256").update(A([fd(d),qi(d)])).digest("hex")])),o=r?.policy_serialized===i?r:void 0,s=o?cA(o,a):new Set,c=_d(t.policy,o?n.filter(d=>s.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return ic={pm_root:e,policy_serialized:i,item_fingerprints:a,index:c},c}async function lA(e,t){let n=sA(e),i=await Ii(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?gd(dA(t,n,i.items),n.change,{cursor:n.cursor,limit:n.limit}):O_(n.policy,i.items,n)}catch(r){return j_(r)}}async function uA(e,t={},n={}){let i=QR(e.action),r=M(process.cwd(),t.path);if(i==="presets"||i==="apply"||i==="derive"||i==="promote")return aA(i,e,r);if(i==="verdicts")return rA(e,r);if(i==="run")return oA(e,r,n);if(["risk","lineages"].includes(i))return lA(e,r);let a=eA(e.kind);if(i==="list")return Jn(r,a);if(!e.id)return $n("id",`assurance ${i} requires an id`,`pm assurance ${i} ${a} <id>`);let o=e.id;if(i==="show")return M_(r,a,o);if(i==="remove"){let l=await dn(()=>Bl(r,a,o,{author:e.author,message:e.message}));return N_(l,e.idOnly)}let s=tA(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 iA(r,s)}:{}},d=await dn(()=>wr(r,a,s,c));return N_(d,e.idOnly)}function ZH(e,t,n){let i={...e,...t};return uA({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:Va(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 Tn from"node:fs/promises";import ka from"node:path";import ba from"node:fs/promises";import oc 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 mA=864e5;function pA(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 fA(e,t){let n;try{n=await ba.readdir(e,{withFileTypes:!0})}catch(r){if(j(r))return[];throw r}let i=[];for(let r of n)if(r.isDirectory()){let a=oc.join(e,r.name),o;try{o=await ba.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 F_(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),a=Math.max(0,t.retentionDays)*mA,o=oc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await fA(o,s.warnings);for(let d of c){let l=oc.join(o,d),u=`checkpoints/${d}`;s.scanned+=1,i?.onRead&&s.warnings.push(...await i.onRead(l));let m;try{m=await ba.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=pA(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 ba.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 sc from"node:fs/promises";import U_ 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 hA=1440*60*1e3,_A=new Set(["committed","compensated"]);function gA(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 yA(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 _A.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 wA(e,t,n,i){let r=i.hooks?.onRead?await i.hooks.onRead(e):[],a=gA(await sc.readFile(e,"utf8")),o=yA(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 sc.rm(e,{force:!0}),i.hooks?.onWrite&&r.push(...await i.hooks.onWrite(e))),{decision:o,warnings:r}}async function H_(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),a=Math.max(0,t.retentionDays)*hA,o=U_.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await sc.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=U_.join(o,d),u=`transactions/sdk/${d}`,m=await wA(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 Ri=["index","embeddings","runtime","locks","checkpoints","transactions"],vA=1440*60*1e3,bA=[{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 kA(e,t,n){let i=t.relativePath,r=ka.join(e,i),a=await Ne({path:r,scope:"project"});try{let o=await Tn.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 Tn.unlink(r):await Tn.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 EA(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],i=[],r=[],a=[],o=Date.now()-vA;for(let s of n){let c=ka.join(e,s.relativePath);if(!await D(c))continue;let d=(await Tn.readdir(c)).filter(l=>l.startsWith(s.prefix)).sort();for(let l of d){let u=ka.posix.join(s.relativePath,l),m=ka.join(c,l);a.push(...await Ne({path:m,scope:"project"}));let f=await Tn.stat(m).catch(p=>{if(!j(p))throw p});if(f){if(f.mtimeMs>o){r.push(u);continue}i.push(u),!t&&(await Tn.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 SA(e){if(!e||e.length===0)return[...Ri];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 (${Ri.join(",")})`,y.USAGE);let n=new Set;for(let i of t){if(!Ri.includes(i))throw new g(`Invalid --scope value "${i}". Expected one or more of: ${Ri.join(", ")}`,y.USAGE);n.add(i)}return Ri.filter(i=>n.has(i))}function xA(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 bz(e,t={}){let n=M(process.cwd(),e.path);await te(n);let i=await $(n),r=t.dryRun===!0,a=SA(t.scope),o=bA.filter(p=>a.includes(p.scope)),s=[],c=[],d=[];for(let p of o){let h=await kA(n,p,r);h.removed?s.push(p.relativePath):c.push(p.relativePath),d.push(...h.warnings)}if(a.includes("runtime")){let p=await EA(n,r);s.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(a.includes("locks")){let p=await Qu(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 H_(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 F_(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 Wi({mode:r?"gc:dry-run":"gc",total_items:o.length}));let f=xA({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:T()}}import{execFile as IA}from"node:child_process";import RA from"node:path";import{promisify as AA}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 CA=AA(IA),W_="@unbrained/pm-cli",$A="latest",TA={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 Sa(e){return e.trim().toLowerCase()}function q_(e,t){let n=Sa(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"&&Sa(i)===n)}function DA(e,t){let n=M(process.cwd(),t.path),i=Bt(n,process.cwd());return{selected_root:e==="global"?i.global:i.project}}async function OA(e,t,n){try{let i=await CA(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
58
|
${a}`,y.GENERIC_FAILURE)}}function xa(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():$A}function Ea(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():W_}async function PA(e,t){let n=e.commandRunner??OA,i=Ea(e),r=xa(e),a=`${i}@${r}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=Ic(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:i,target:a,command:o,before_version:s,...i===W_?{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 LA(e){return RA.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function NA(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!LA(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 MA(e,t){let n=NA(e,t);return e.kind!=="local"||await D(n)?n:await D(e.location)?e.location:n}function jA(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 G_(e,t){let n=DA(e,t);return(await he(n.selected_root)).state.entries.filter(i=>i.scope===e)}async function FA(e,t,n){let i=await G_(e,t);return i.find(r=>q_(r,n.name))??i.find(r=>Sa(r.directory)===Sa(n.directory))}async function UA(e,t,n,i,r){let a=xa(t),o=await MA(e.source,a),s=jA(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 ns(o,{install:!0,project:i==="project",global:i==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let d=await FA(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 HA(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 Cz(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",...TA[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:de(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 PA(t,a):{requested:!1,status:"skipped",package:Ea(t),target:`${Ea(t)}@${xa(t)}`,command:["npm","install","-g",`${Ea(t)}@${xa(t)}`],repair:t.repair===!0,reason:"not_requested"},d=s?await G_(r,n):[];if(i&&(d=d.filter(m=>q_(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 UA(m,t,n,r,a));let u=HA(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 zA}from"node:crypto";import{isUtf8 as WA}from"node:buffer";import Ai from"node:fs/promises";import cc 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 B_(e){try{return(await Ai.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(j(t))return[];throw t}}function qA(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 GA(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!WA(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 Hn(i).ok?qA(e,i,t.length,n):null}catch{return null}}async function dc(e,t){if(!(await Ai.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=cc.join(e,"history"),i=await B_(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=cc.join(n,o);try{let l=await Ai.lstat(d);if(r.set(o,A([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await Ai.readFile(d);c.digest=zA(t).update(u).digest("hex"),c.stream=GA(s,u,c.digest)}catch{}}if(A(i)!==A(await B_(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of r){let c=await Ai.lstat(cc.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 lc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Dn(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function BA(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:Dn(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||Dn(e.latest_record_hash,e.latest_hash_algorithm))}function JA(e){return e===null?!0:!lc(e)||!uc(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||Dn(e.record_hash,"sha256")||Dn(e.record_hash,"sha512"))}function VA(e,t){return!lc(e)||!uc(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)&&Dn(e.stream_digest,t)&&BA(e)&&(e.checkpoint_digest===null||Dn(e.checkpoint_digest,"sha256"))&&JA(e.last_maintenance)}function J_(e){if(!lc(e)||!uc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Ua.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(!VA(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(Ha(A(r),t)!==i)throw new TypeError("History attestation rollup mismatch");return e}async function V_(e={}){let t=Re(e.hashAlgorithm),n=e.generatedAt??T();if(!wt(n))throw new TypeError("Invalid history attestation timestamp");let i=await dc(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:Ua.format,version:1,hash_algorithm:t,generated_at:n,streams:i.map(o=>o.stream)};return J_({...a,workspace_digest:Ha(A(a),t)})}async function K_(e,t={}){let n=J_(e),i=await dc(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 Y_ 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 Qz(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 Y_.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 K_(i,{pmRoot:t.path})}let n=await V_({pmRoot:t.path,hashAlgorithm:Re(e.hashAlgorithm)});if(e.output===void 0)return n;try{await Y_.writeFile(e.output,`${JSON.stringify(n,null,2)}
|
|
@@ -61,5 +61,5 @@ ${a}`,y.GENERIC_FAILURE)}}function xa(e){return typeof e.tag=="string"&&e.tag.tr
|
|
|
61
61
|
`)}catch{}}function ZA(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 QA(e,t,n,i){let r=[];return{candidates:await il(e,t,n,r,i),warnings:r}}async function hc(e,t,n,i,r){let a=qt(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 KA.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:${Ci.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function eC(e,t,n){let i=e.metadata;return{id:i.id,mode:t,updated_at:i.updated_at,corpus:ol(e,{fields:n})}}var On=Y;function tC(e){let t=F(),n=On(e.search?.provider);if(!n)return null;let i=xd(t,n);if(!i)return null;let r=i.runtime_definition??i.definition,a=On(r.name)??On(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 nC(e){let t=F(),n=On(e.vector_store?.adapter);if(!n)return null;let i=Id(t,n);if(!i)return null;let r=i.runtime_definition??i.definition,a=On(r.name)??On(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 fc(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 iC(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)=>fc(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(fc(s,`extension search provider "${e.name}" embed output at index ${a}`))}return r}function eg(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function tg(e,t,n){let i=n?Nt(n.name,eg(e)):t?Nt(t.name,t.model):null;if(!i)throw new g("No embedding identity available for semantic reindex mode",y.USAGE);return i}function rC(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,i)=>n.localeCompare(i))}async function ng(e,t,n,i,r,a,o,s){let c=i?.name??n?.name,d=sl(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Ga(e),u=r.map(p=>cl(p,{providerName:c,maxCharacters:d,fields:l})),m=[],f=null;if(i)try{m=await iC(i,e,u),f=Nt(i.name,eg(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 dl(n,e,u,{onProgress:h=>{h.phase==="complete"&&(o.batches_completed=h.batch_index),ae(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=Nt(n.name,n.model)}if(ae(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 aC(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 ml(e,o,{},a)}async function ig(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 ul(e,n)}}function oC(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function sC(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 cC(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=zn(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=mr(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 dC(e){let t=H(e.settings,F()),n=await QA(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 lC(e){let t=await an(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 tg(e.settings,zn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&rn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(YA))}async function uC(e){let t=await an(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=tg(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),i=new Set(e.metadataDocuments.map(d=>d.metadata.id)),r=rC(t.entries,i),a=rn(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 hc(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 mC(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await hc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,ae(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let i=await ng(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...i,staleDocuments:n,vectorDimension:Ba(i.vectors,"Reindex embeddings")}}async function pC(e){let t=await ng(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,i=t.embeddingIdentity,r=Ba(n,"Reindex embeddings");if(!(!e.resetRequired&&(rn(e.ledgerEmbedding,i)||fl(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:i,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let a=await mC(e);return n=a.vectors,i=a.embeddingIdentity,r=a.vectorDimension,{vectors:n,embeddingIdentity:i,staleDocuments:a.staleDocuments,vectorDimension:r,resetRequired:!0}}async function fC(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(ae(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,ae(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)})`),ae(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){ae(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await ll(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,ae(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 hC(e,t){return e.map((n,i)=>({id:n.metadata.id,vector:fc(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 _C(e){ae(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await pC({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?(ae(e.progressEnabled,"vector_reset_start"),await aC(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),ae(e.progressEnabled,"vector_reset_complete")):await ig(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=hC(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await fC({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:pl(t.embeddingIdentity,t.vectorDimension)}}async function gC(e){let t=await uC(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(ae(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 ae(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await ig(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let i=await _C({...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 yC(e){let t=Ci.join(e.pmRoot,mc),n=Ci.join(e.pmRoot,pc),i=Ga(e.settings),r=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(eC(o,e.mode,i))).join(`
|
|
62
62
|
`);ae(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{ae(e.progressEnabled,"writing vectorization status ledger"),await hl(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 vW(e,t){let n=ZA(e.mode),i=XA(e),r=e.full===!0;ae(i,`start mode=${n}`);let a=M(process.cwd(),t.path);await te(a);let o=dr(await $(a)).settings,s=null;try{s=await ie(a,Vd,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=tC(o),d=nC(o),l=cC({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ae(i,"loading item corpus");let m=await dC({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;ae(i,`loaded_items=${h.length}`);let _=T(),w=sC(u,_,h),v=Ci.join(a,mc),E=Ci.join(a,pc),k=u==="keyword"?await hc(a,p,o.schema,f):h,I=[],C={},S=null,b=oC(u);if(u==="keyword"&&await lC({pmRoot:a,settings:o,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let x=await gC({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 yC({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 Wi({mode:u,total_items:h.length})];return ae(i,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:mc,embeddings:pc},warnings:[...f,...I,...O,...P],generated_at:_}}finally{await s?.()}}export{L as a,we as b,Ke as c,dn as d,Xa as e,Ol as f,Mt as g,Za as h,fg as i,to as j,no as k,Ml as l,un as m,Bn as n,ro as o,Og as p,Wl as q,Jn as r,Gl as s,wr as t,ao as u,Bl as v,Jl as w,Vl as x,lm as y,Ng as z,OC as A,Xl as B,Fg as C,QC as D,nv as E,OD as F,ND as G,MD as H,ri as I,jD as J,FD as K,UD as L,HD as M,zD as N,WD as O,qD as P,GD as Q,BD as R,JD as S,VD as T,Vo as U,ns as V,aT as W,Uu as X,Wg as Y,iu as Z,u$ as _,Xn as $,m$ as aa,Yg as ba,Xg as ca,p$ as da,Zg as ea,Ph as fa,y$ as ga,lu as ha,Nh as ia,NF as ja,MF as ka,Zn as la,kr as ma,mu as na,pu as oa,fu as pa,hu as qa,wu as ra,bu as sa,ku as ta,xu as ua,At as va,GN as wa,BN as xa,JN as ya,VN as za,nM as Aa,xf as Ba,ra as Ca,IM as Da,pt as Ea,Pf as Fa,RM as Ga,AM as Ha,JS as Ia,XS as Ja,Ff as Ka,yy as La,Ru as Ma,ys as Na,
|
|
65
|
-
//# sourceMappingURL=chunk-
|
|
64
|
+
`);let a=[];if(e.mode!=="keyword")try{ae(e.progressEnabled,"writing vectorization status ledger"),await hl(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 vW(e,t){let n=ZA(e.mode),i=XA(e),r=e.full===!0;ae(i,`start mode=${n}`);let a=M(process.cwd(),t.path);await te(a);let o=dr(await $(a)).settings,s=null;try{s=await ie(a,Vd,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=tC(o),d=nC(o),l=cC({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ae(i,"loading item corpus");let m=await dC({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;ae(i,`loaded_items=${h.length}`);let _=T(),w=sC(u,_,h),v=Ci.join(a,mc),E=Ci.join(a,pc),k=u==="keyword"?await hc(a,p,o.schema,f):h,I=[],C={},S=null,b=oC(u);if(u==="keyword"&&await lC({pmRoot:a,settings:o,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let x=await gC({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 yC({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 Wi({mode:u,total_items:h.length})];return ae(i,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:mc,embeddings:pc},warnings:[...f,...I,...O,...P],generated_at:_}}finally{await s?.()}}export{L as a,we as b,Ke as c,dn as d,Xa as e,Ol as f,Mt as g,Za as h,fg as i,to as j,no as k,Ml as l,un as m,Bn as n,ro as o,Og as p,Wl as q,Jn as r,Gl as s,wr as t,ao as u,Bl as v,Jl as w,Vl as x,lm as y,Ng as z,OC as A,Xl as B,Fg as C,QC as D,nv as E,OD as F,ND as G,MD as H,ri as I,jD as J,FD as K,UD as L,HD as M,zD as N,WD as O,qD as P,GD as Q,BD as R,JD as S,VD as T,Vo as U,ns as V,aT as W,Uu as X,Wg as Y,iu as Z,u$ as _,Xn as $,m$ as aa,Yg as ba,Xg as ca,p$ as da,Zg as ea,Ph as fa,y$ as ga,lu as ha,Nh as ia,NF as ja,MF as ka,Zn as la,kr as ma,mu as na,pu as oa,fu as pa,hu as qa,wu as ra,bu as sa,ku as ta,xu as ua,At as va,GN as wa,BN as xa,JN as ya,VN as za,nM as Aa,xf as Ba,ra as Ca,IM as Da,pt as Ea,Pf as Fa,RM as Ga,AM as Ha,JS as Ia,XS as Ja,Ff as Ka,yy as La,Ru as Ma,ys as Na,b1 as Oa,k1 as Pa,Sr as Qa,xr as Ra,ch as Sa,kj as Ta,dh as Ua,uh as Va,mh as Wa,hh as Xa,gh as Ya,_I as Za,gI as _a,HF as $a,zF as ab,WF as bb,qF as cb,wI as db,vI as eb,bI as fb,GF as gb,Fh as hb,EI as ib,Uh as jb,js as kb,zh as lb,SI as mb,xI as nb,II as ob,zs as pb,Ws as qb,nU as rb,iU as sb,rU as tb,iR as ub,hH as vb,C_ as wb,Ii as xb,D_ as yb,O_ as zb,P_ as Ab,rc as Bb,uA as Cb,ZH as Db,bz as Eb,Cz as Fb,J_ as Gb,V_ as Hb,K_ as Ib,Qz as Jb,mW as Kb,pW as Lb,fW as Mb,vW as Nb};
|
|
65
|
+
//# sourceMappingURL=chunk-ADSBGYLW.js.map
|