@unbrained/pm-cli 2026.10.19 → 2026.10.20
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 +33 -0
- package/dist/cli/error-guidance.d.ts +7 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QBNEZII5.js → chunk-2GGGOD7P.js} +13 -13
- package/dist/cli-bundle/chunks/{chunk-4CXQSRSP.js → chunk-7NHA5K77.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NX7Q4LGN.js → chunk-7ZOIZ2AZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6DS5CAN2.js → chunk-GHJOMRSF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O2ZRRLAP.js → chunk-KU4Q3MSI.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-DMFM5R4G.js → chunk-LS55VKRK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QG4LMU7A.js → chunk-PNPE2OVJ.js} +43 -43
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-LBEMB3BW.js → chunk-QETMESEB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4MJ6WBMA.js → chunk-QMZ73FCW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TZU6U5ZE.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-H3XYP24A.js → chunk-VLJLWZBO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-XAWE4EAK.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YECCKB4E.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-5GZSX5HU.js → chunk-YT2Z3JPC.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-4XFVAXA4.js → chunk-YTHI5DTH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D3EDNAN7.js → chunk-YW6SIKYP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XH7C3A5N.js → chunk-ZA3XXHEE.js} +6 -6
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +2 -0
- package/dist/cli-bundle/{focused-chunks/indexed-receipt-blobs-QW2VWWJE.js → chunks/indexed-receipt-blobs-U7VGKIYC.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-WQUVDJIH.js → register-list-query-NNDV6F6I.js} +3 -3
- package/dist/cli-bundle/chunks/{register-mutation-IWIBQIO3.js → register-mutation-3GCBSNQS.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-UNFMCKKQ.js → settlement-hook-CLRGA6O7.js} +2 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WZTEFFQI.js → chunk-37SU7BZI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5YTOYBTZ.js → chunk-6IU7BESB.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +25 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PXDR77TO.js → chunk-AW35RDKA.js} +22 -22
- package/dist/cli-bundle/focused-chunks/{chunk-RLRMNFLF.js → chunk-E4II2D2B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FEN7WOOP.js → chunk-F7FD25TG.js} +12 -12
- package/dist/cli-bundle/focused-chunks/{chunk-JDBO7SMR.js → chunk-GYHZ7W6O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EOQ6W25I.js → chunk-H5Q2HUU6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3TEIACFU.js → chunk-HUZAXSIJ.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-JBJJW2WL.js → chunk-J6EYUGAR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ENZMATOY.js → chunk-KDGUIIRU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-H6BVQ63U.js → chunk-KKRFSI2N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GWTV45SB.js → chunk-LJPUJ2KK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HYMYAGSY.js → chunk-NI6NS44Q.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-L4PL3GZR.js → chunk-VAYS754X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SKYLOPU2.js → chunk-VLSER3XW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JCLC6HKT.js → chunk-VS6VTWTZ.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-OV2WVLUR.js → chunk-ZGEK57KD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +2 -0
- package/dist/cli-bundle/{chunks/indexed-receipt-blobs-BVSHK4WQ.js → focused-chunks/indexed-receipt-blobs-H2G6CCGO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-X4FNHTOD.js → settlement-hook-5SNBBT7C.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-MZSVQYO4.js → stage-EMTISXR7.js} +2 -2
- package/dist/cli-bundle/main.js +21 -21
- 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 +21 -21
- 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 +55 -55
- 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 +8 -8
- package/dist/core/fs/fs-utils.d.ts +2 -2
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/event-index.js +2 -2
- package/dist/core/output/output.d.ts +7 -2
- package/dist/core/output/output.js +5 -5
- package/dist/core/shared/errors.d.ts +48 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings.js +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.d.ts +21 -0
- package/dist/sdk/dependencies/context-budget-recovery.js +2 -0
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/errors.d.ts +4 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +13 -0
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.d.ts +14 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/output/list-envelope.d.ts +7 -0
- package/dist/sdk/output/list-envelope.js +2 -0
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/relationship-context.d.ts +2 -0
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +2 -0
- package/dist/sdk/structured-mutations.js +1 -1
- package/docs/COMMANDS.md +14 -0
- package/docs/PR_REVIEW_LOOP.md +32 -12
- package/docs/SCRIPTING.md +10 -0
- package/docs/SDK.md +77 -0
- package/docs/TESTING.md +25 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4ICKT4GH.js +0 -3
- package/dist/cli-bundle/chunks/chunk-OEJ3G7XT.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QKAAZWGC.js +0 -3
- package/dist/cli-bundle/chunks/chunk-TK3G3GAP.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-SUWOZNDU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-QGM5YJW7.js +0 -2
- package/dist/cli-bundle/chunks/stage-7DELI4Z5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2IEWB6MB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BJMPRB7A.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KLJN44VY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-Y54ONBEX.js +0 -25
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as Rt,d as fn,e as hn,f as _n,g as Vl}from"./chunk-JCLC6HKT.js";import{a as Ga,c as Hr,d as zr,e as hd,g as _d,h as Ja,i as gd,j as rn,k as an,l as yd,m as wd,n as Va,o as kd,p as on,q as sn,r as Sd,s as Ed,t as Ka}from"./chunk-HYMYAGSY.js";import{e as Yr,f as Xa,h as Za}from"./chunk-JDBO7SMR.js";import{B as Dd,C as Jr,D as Pd,E as Ya,G as Nd,H as Ld,J as Md,K as jd,L as Vr,O as Kr,a as dd,g as qa,i as ld}from"./chunk-WZTEFFQI.js";import{K as Kl}from"./chunk-L4PL3GZR.js";import{D as io,E as pi,Fa as jl,Ga as Fl,Ka as Ul,La as Hl,T as fi,U as fl,V as ao,W as Gn,Y as oo,aa as Al,ba as Il,ca as Rl,da as Cl,ea as gi,f as il,g as al,ga as Tl,h as ol,ha as $l,i as sl,ia as Ol,ib as ql,ja as Wt,k as mi,ka as Dl,kb as lo,la as mn,lb as Gl,ma as Pl,mb as Bl,na as so,o as Wn,oa as pn,p as cl,pa as Nl,q as dl,qa as Ll,r as qn,ra as Ml,s as ll,sa as co,u as ro,ub as uo,v as ul,z as ml}from"./chunk-ENZMATOY.js";import{a as ud,b as nn,c as Ba,d as md,e as pd,f as it,g as Wr,h as fd,i as St}from"./chunk-H6BVQ63U.js";import{$ as yi,B as Sl,C as we,D as ve,E as El,F as _i,G as ot,H as st,K as xl,L as ct,Z as Bn,a as ui,c as pl,ga as zl,j as hl,ja as Wl,k as _l,m as gl,n as yl,o as It,p as wl,q as vl,t as bl,u as kl,z as hi}from"./chunk-BJMPRB7A.js";import{$ as Wd,$a as li,Aa as ln,Ba as Qd,D as G,Da as ii,E as Fd,Ea as ai,Fa as to,Ga as At,H as Re,Ha as zn,I as Qa,Ia as el,Ja as oi,Ka as zt,La as se,Ma as si,N as Xr,Na as tl,O as Hn,Oa as no,P as Ud,Pa as ci,Q as Zr,Qa as un,R as Hd,Ra as di,Sa as nl,T as Qr,U as ei,W as zd,Wa as He,X as Ne,Za as rl,_ as xt,_a as $,aa as qd,ba as Gd,ca as at,da as Bd,db as re,ja as Jd,ka as eo,la as ti,ma as dn,oa as ni,pa as Vd,qa as Kd,sa as Yd,ua as Xd,wa as Zd,ya as ri}from"./chunk-PXDR77TO.js";import{b as en}from"./chunk-GWTV45SB.js";import{a as de,c as De,e as Ie,f as Xe,j as _e,k as vd,l as qr,n as bd}from"./chunk-RLRMNFLF.js";import{Ba as Yc,Bb as ad,Ca as Ft,Cb as od,Cc as $d,Dc as Pe,Ea as Xc,Fa as C,Fd as oe,Ga as Zc,Ha as Ae,Ja as Ur,Ka as Qc,Kb as sd,La as Ua,Lb as Ut,Ma as Ha,Na as za,Nb as Wa,O as Wc,Ob as cd,Pa as ed,Pb as tn,Qa as td,R as qc,Rb as Ke,T as Fa,Ta as nd,Tb as Ye,Wb as xd,Y as pe,Yb as Gr,Z as Je,Zb as Ad,_ as Gc,_b as Id,a as Nc,aa as Z,ac as Rd,bb as rd,d as Lc,da as Bc,e as Mc,ia as Jc,ic as H,kb as id,lc as Y,nc as Ue,o as ja,oa as Vc,oc as Cd,pa as Kc,pc as Br,qa as W,va as Un,vd as T,wa as j,wc as Td,wd as Od,xa as Ve,xd as cn,ya as Fr,yd as Et,za as jt,zd as Ht}from"./chunk-Y54ONBEX.js";import{a as Jn}from"./chunk-VVRXF4JO.js";import{a as Jl}from"./chunk-JBJJW2WL.js";import{A as Fn,B as D,C as kt,D as U,E as V,H as ee,a as Lr,d as Mr,o as jc,q as Fc,s as Uc,u as Hc,v as jr,w as zc,y as g,z as y}from"./chunk-3TEIACFU.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"}},Ce=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ze=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 gn(e){try{return await e()}catch(t){throw t instanceof L?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Yl(e){try{return await e()}catch(t){throw t instanceof Ce?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as $g}from"node:crypto";import Og 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 yn=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]="416aaf09-e4f6-5d10-aee0-eba374f1cd83")}catch{}})();var Zl=1,qt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],mo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Dg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Pg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,wi=30,vi=5e3,Ql=4,Ng=50;function dt(e,t){if(!Pg.test(e))throw new L(`${t} must be a stable lowercase id`)}function Lg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Vn(e){let t=Dg.filter(i=>e[i]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function fo(e,t){return C(e)===C(t)}function eu(e,t){if(t.polarity==="equals")return fo(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function tu(e){let t=Vn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>eu(r.observed,t)===(r.expected==="pass"))}function Mg(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!fo(e.value,t.value)}function jg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||C(e.scope)!==C(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Mg(Vn(e),Vn(t))||n[t.enforcement]<n[e.enforcement]||r}function Fg(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,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new L("items source equals/state requires field")}function Ug(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 Hg(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 ho(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&Lg(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 ${mo.join(", ")}`);let n=Reflect.get(t,"kind");if(!mo.includes(n))throw new L(`measurement.source.kind must be one of ${mo.join(", ")}`);let r=t;if(r.kind==="items"&&Fg(r),r.kind==="dependency_kind"&&Ug(r),r.kind==="prose_edge_gap"&&Hg(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new L(`${r.kind} source requires field`);return r.kind==="provider"&&(dt(r.provider,"provider source provider"),dt(r.key,"provider source key")),e}function _o(e){if(dt(e.id,"assertion.id"),dt(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=Vn(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"&&dt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new L("assertion negative control requires pass and fail cases");if(!tu(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function zg(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)dt(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(!qt.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 nu(e){if(dt(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)dt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${qt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!qt.includes(t))throw new L(`gate trigger must be one of ${qt.join(", ")}`);return e.provider_policy&&zg(e.provider_policy),e}function wn(e){if(e.version!==Zl)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(ho(r),t.has(`measurement:${r.id}`))throw new L(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(_o(r),t.has(`assertion:${r.id}`))throw new L(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){nu(r);let i=r.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(i.length>0)throw new L(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new L(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of ru(e))if(!n.has(r))throw new L(`${i.join(", ")} references missing measurement ${r}`);return e}function go(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)go(n,t)}function ru(e){let t=new Map,n=(r,i)=>{let a=t.get(r)??[];a.push(i),t.set(r,a)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];go(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.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]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let a=n.pop();if(r.has(a))continue;r.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&go(o.source.expression,n)}return i}function Kn(){return{version:Zl,measurements:[],assertions:[],gates:[]}}function qg(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let a=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?a:!a}return fo(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Gg(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 Bg(e,t){let n=[],r=Fa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[]){let o=Fa(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===r&&Gg(e,s)&&n.push(`${i.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Jg(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let a=Reflect.get(i,"text");typeof a=="string"&&t.push(a)}}}return t}function Vg(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function po(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Kg(e){let t=new Map,n=new Set,r=[],i=/(?<![\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(po(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(po(o.id,s));for(let s of Jg(o)){let c=[...s.matchAll(i)].map(d=>d[0]);a+=c.length,r.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:a}}function Yg(e,t){let n=Kg(t.items),r=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=po(o.holder_id,d);if(n.linked_pairs.has(l)||Vg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],a=i.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:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function Xg(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 Zg(e,t){let n=t.items.filter(r=>{let i=r[e.link],a=Array.isArray(i)&&i.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Qg(e,t){let n=e.source;return n.kind==="items"?qg(n,t):n.kind==="dependency_kind"?Bg(n,t):n.kind==="prose_edge_gap"?Yg(n,t):n.kind==="history"?Xg(n,t):n.kind==="links"?Zg(n,t):null}function iu(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function ey(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function au(e,t,n){let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(a),r}async function ou(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await su(o,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[s.cost];return i.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await au(e.operands,Ql,o=>ou(o,t,n,r,i));return{value:ey(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 ty(e,t,n,r,i){ho(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await ou(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Qg(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=iu([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Ce(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${$g("sha256").update(C(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function su(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let a=i.cache.get(e.id);if(a)return a;let o=ty(e,t,n,r,i).catch(s=>{if(s instanceof Ze&&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 Ze(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,o),o}async function yo(e,t,n=[e]){return su(e,t,n,[],{cache:new Map,charged:new Set})}function ny(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 ry(e,t,n={}){_o(e);let r=Vn(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:ny(t.value,r),verdict:i?"retired":eu(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:tu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function iy(e,t,n,r){let i=Wg(e,t);if(i.size===0)return;let a=e.provider_policy,o=a?.triggers[r];if(!a||!o)throw new Ce(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!s.has(d))throw new Ce(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Ce(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new Ce(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new Ce(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function Xl(e,t,n,r,i){try{return await yo(n,r,i)}catch(a){if(a instanceof Ze){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new Ce(`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 cu(e,t,n,r){wn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Ce(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Ce(`assurance gate ${e} does not declare trigger ${r.trigger}`);iy(i,t,n,r.trigger);let a=await au(i.assertion_ids,Ql,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 Xl(i.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 ry(d,await Xl(i.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:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.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:iu(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function bi(e){return Og.join(e,"assurance.json")}async function du(e){let t=await V(bi(e));return t===null?Kn():ki(t)}function ki(e){try{return wn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.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 Si(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function ay(e,t){e==="measurement"?ho(t):e==="assertion"?_o(t):nu(t)}async function Yn(e,t){let n=structuredClone(Si(await du(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function wo(e,t,n){let r=Si(await du(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ei(e,t,n,r={}){ay(t,n);let i=await $(e),a=G(r.author,i.author_default),o=await un({pmRoot:e,filePath:bi(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:wi,lockWaitMs:vi,mutate:s=>{let c=s===null?Kn():ki(s),d=Si(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&jg(d[l],n)){let m=n.authorization_decision;if(!m||!r.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),wn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
1
|
+
import{c as Rt,d as fn,e as hn,f as _n,g as Vl}from"./chunk-VS6VTWTZ.js";import{a as Jl}from"./chunk-J6EYUGAR.js";import{a as Ga,c as Hr,d as zr,e as hd,g as _d,h as Ja,i as gd,j as rn,k as an,l as yd,m as wd,n as Va,o as kd,p as on,q as sn,r as Sd,s as Ed,t as Ka}from"./chunk-NI6NS44Q.js";import{e as Yr,f as Xa,h as Za}from"./chunk-GYHZ7W6O.js";import{B as Dd,C as Jr,D as Pd,E as Ya,G as Nd,H as Ld,J as Md,K as jd,L as Vr,O as Kr,a as dd,g as qa,i as ld}from"./chunk-37SU7BZI.js";import{K as Kl}from"./chunk-VAYS754X.js";import{D as io,E as pi,Fa as jl,Ga as Fl,Ka as Ul,La as Hl,T as fi,U as fl,V as ao,W as Gn,Y as oo,aa as Al,ba as Il,ca as Rl,da as Cl,ea as gi,f as il,g as al,ga as Tl,h as ol,ha as $l,i as sl,ia as Ol,ib as ql,ja as Wt,k as mi,ka as Dl,kb as lo,la as mn,lb as Gl,ma as Pl,mb as Bl,na as so,o as Wn,oa as pn,p as cl,pa as Nl,q as dl,qa as Ll,r as qn,ra as Ml,s as ll,sa as co,u as ro,ub as uo,v as ul,z as ml}from"./chunk-KDGUIIRU.js";import{a as ud,b as nn,c as Ba,d as md,e as pd,f as it,g as Wr,h as fd,i as St}from"./chunk-KKRFSI2N.js";import{$ as yi,B as Sl,C as we,D as ve,E as El,F as _i,G as ot,H as st,K as xl,L as ct,Z as Bn,a as ui,c as pl,ga as zl,j as hl,ja as Wl,k as _l,m as gl,n as yl,o as It,p as wl,q as vl,t as bl,u as kl,z as hi}from"./chunk-JEXZEIAX.js";import{$ as Wd,$a as li,Aa as ln,Ba as Qd,D as G,Da as ii,E as Fd,Ea as ai,Fa as to,Ga as At,H as Re,Ha as zn,I as Qa,Ia as el,Ja as oi,Ka as zt,La as se,Ma as si,N as Xr,Na as tl,O as Hn,Oa as no,P as Ud,Pa as ci,Q as Zr,Qa as un,R as Hd,Ra as di,Sa as nl,T as Qr,U as ei,W as zd,Wa as He,X as Ne,Za as rl,_ as xt,_a as $,aa as qd,ba as Gd,ca as at,da as Bd,db as re,ja as Jd,ka as eo,la as ti,ma as dn,oa as ni,pa as Vd,qa as Kd,sa as Yd,ua as Xd,wa as Zd,ya as ri}from"./chunk-AW35RDKA.js";import{b as en}from"./chunk-LJPUJ2KK.js";import{a as de,c as De,e as Ie,f as Xe,j as _e,k as vd,l as qr,n as bd}from"./chunk-E4II2D2B.js";import{Ad as Ht,Ba as Yc,Bb as ad,Ca as Ft,Cb as od,Cc as $d,Dc as Pe,Ea as Xc,Fa as C,Ga as Zc,Gd as oe,Ha as Ae,Ja as Ur,Ka as Qc,Kb as sd,La as Ua,Lb as Ut,Ma as Ha,Na as za,Nb as Wa,O as Wc,Ob as cd,Pa as ed,Pb as tn,Qa as td,R as qc,Rb as Ke,T as Fa,Ta as nd,Tb as Ye,Wb as xd,Y as pe,Yb as Gr,Z as Je,Zb as Ad,_ as Gc,_b as Id,a as Nc,aa as Z,ac as Rd,bb as rd,d as Lc,da as Bc,e as Mc,ia as Jc,ic as H,kb as id,mc as Y,o as ja,oa as Vc,oc as Ue,pa as Kc,pc as Cd,qa as W,qc as Br,va as Un,wa as j,wd as T,xa as Ve,xc as Td,xd as Od,ya as Fr,yd as cn,za as jt,zd as Et}from"./chunk-AS3MOBO3.js";import{a as Jn}from"./chunk-VVRXF4JO.js";import{A as Fn,B as D,C as kt,D as U,E as V,H as ee,a as Lr,d as Mr,o as jc,q as Fc,s as Uc,u as Hc,v as jr,w as zc,y as g,z as y}from"./chunk-HUZAXSIJ.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"}},Ce=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ze=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 gn(e){try{return await e()}catch(t){throw t instanceof L?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Yl(e){try{return await e()}catch(t){throw t instanceof Ce?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as $g}from"node:crypto";import Og 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 yn=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]="416aaf09-e4f6-5d10-aee0-eba374f1cd83")}catch{}})();var Zl=1,qt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],mo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Dg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Pg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,wi=30,vi=5e3,Ql=4,Ng=50;function dt(e,t){if(!Pg.test(e))throw new L(`${t} must be a stable lowercase id`)}function Lg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Vn(e){let t=Dg.filter(i=>e[i]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function fo(e,t){return C(e)===C(t)}function eu(e,t){if(t.polarity==="equals")return fo(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function tu(e){let t=Vn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>eu(r.observed,t)===(r.expected==="pass"))}function Mg(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!fo(e.value,t.value)}function jg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||C(e.scope)!==C(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Mg(Vn(e),Vn(t))||n[t.enforcement]<n[e.enforcement]||r}function Fg(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,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new L("items source equals/state requires field")}function Ug(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 Hg(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 ho(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&Lg(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 ${mo.join(", ")}`);let n=Reflect.get(t,"kind");if(!mo.includes(n))throw new L(`measurement.source.kind must be one of ${mo.join(", ")}`);let r=t;if(r.kind==="items"&&Fg(r),r.kind==="dependency_kind"&&Ug(r),r.kind==="prose_edge_gap"&&Hg(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new L(`${r.kind} source requires field`);return r.kind==="provider"&&(dt(r.provider,"provider source provider"),dt(r.key,"provider source key")),e}function _o(e){if(dt(e.id,"assertion.id"),dt(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=Vn(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"&&dt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new L("assertion negative control requires pass and fail cases");if(!tu(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function zg(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)dt(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(!qt.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 nu(e){if(dt(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)dt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${qt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!qt.includes(t))throw new L(`gate trigger must be one of ${qt.join(", ")}`);return e.provider_policy&&zg(e.provider_policy),e}function wn(e){if(e.version!==Zl)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(ho(r),t.has(`measurement:${r.id}`))throw new L(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(_o(r),t.has(`assertion:${r.id}`))throw new L(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){nu(r);let i=r.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(i.length>0)throw new L(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new L(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of ru(e))if(!n.has(r))throw new L(`${i.join(", ")} references missing measurement ${r}`);return e}function go(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)go(n,t)}function ru(e){let t=new Map,n=(r,i)=>{let a=t.get(r)??[];a.push(i),t.set(r,a)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];go(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.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]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let a=n.pop();if(r.has(a))continue;r.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&go(o.source.expression,n)}return i}function Kn(){return{version:Zl,measurements:[],assertions:[],gates:[]}}function qg(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let a=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?a:!a}return fo(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Gg(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 Bg(e,t){let n=[],r=Fa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[]){let o=Fa(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===r&&Gg(e,s)&&n.push(`${i.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Jg(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let a=Reflect.get(i,"text");typeof a=="string"&&t.push(a)}}}return t}function Vg(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function po(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Kg(e){let t=new Map,n=new Set,r=[],i=/(?<![\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(po(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(po(o.id,s));for(let s of Jg(o)){let c=[...s.matchAll(i)].map(d=>d[0]);a+=c.length,r.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:a}}function Yg(e,t){let n=Kg(t.items),r=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=po(o.holder_id,d);if(n.linked_pairs.has(l)||Vg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],a=i.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:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function Xg(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 Zg(e,t){let n=t.items.filter(r=>{let i=r[e.link],a=Array.isArray(i)&&i.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function Qg(e,t){let n=e.source;return n.kind==="items"?qg(n,t):n.kind==="dependency_kind"?Bg(n,t):n.kind==="prose_edge_gap"?Yg(n,t):n.kind==="history"?Xg(n,t):n.kind==="links"?Zg(n,t):null}function iu(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function ey(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function au(e,t,n){let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(a),r}async function ou(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await su(o,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[s.cost];return i.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await au(e.operands,Ql,o=>ou(o,t,n,r,i));return{value:ey(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 ty(e,t,n,r,i){ho(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await ou(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Qg(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=iu([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Ce(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${$g("sha256").update(C(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function su(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let a=i.cache.get(e.id);if(a)return a;let o=ty(e,t,n,r,i).catch(s=>{if(s instanceof Ze&&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 Ze(s.message,c);throw d.cause=s,d}throw s});return i.cache.set(e.id,o),o}async function yo(e,t,n=[e]){return su(e,t,n,[],{cache:new Map,charged:new Set})}function ny(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 ry(e,t,n={}){_o(e);let r=Vn(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:ny(t.value,r),verdict:i?"retired":eu(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:tu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function iy(e,t,n,r){let i=Wg(e,t);if(i.size===0)return;let a=e.provider_policy,o=a?.triggers[r];if(!a||!o)throw new Ce(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!s.has(d))throw new Ce(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Ce(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new Ce(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new Ce(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function Xl(e,t,n,r,i){try{return await yo(n,r,i)}catch(a){if(a instanceof Ze){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new Ce(`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 cu(e,t,n,r){wn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Ce(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Ce(`assurance gate ${e} does not declare trigger ${r.trigger}`);iy(i,t,n,r.trigger);let a=await au(i.assertion_ids,Ql,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 Xl(i.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 ry(d,await Xl(i.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:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.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:iu(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function bi(e){return Og.join(e,"assurance.json")}async function du(e){let t=await V(bi(e));return t===null?Kn():ki(t)}function ki(e){try{return wn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.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 Si(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function ay(e,t){e==="measurement"?ho(t):e==="assertion"?_o(t):nu(t)}async function Yn(e,t){let n=structuredClone(Si(await du(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function wo(e,t,n){let r=Si(await du(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Ei(e,t,n,r={}){ay(t,n);let i=await $(e),a=G(r.author,i.author_default),o=await un({pmRoot:e,filePath:bi(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:wi,lockWaitMs:vi,mutate:s=>{let c=s===null?Kn():ki(s),d=Si(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&jg(d[l],n)){let m=n.authorization_decision;if(!m||!r.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),wn(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 vo(e,t,n={}){let r=Kn();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),wn(r);let i=await $(e),a=G(n.author,i.author_default),o=await un({pmRoot:e,filePath:bi(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:wi,lockWaitMs:vi,mutate:s=>{let c=s===null?Kn():ki(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(C(_)!==C(h))throw new L(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),wn(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 lu(e,t,n,r={}){let i=await $(e),a=G(r.author,i.author_default),o=await un({pmRoot:e,filePath:bi(e),op:`assurance:${t}:remove`,author:a,message:r.message,lockTtlSeconds:wi,lockWaitMs:vi,mutate:s=>{let c=s===null?Kn():ki(s);if(t==="measurement"){let u=ru(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=Si(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),wn(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 uu(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await $(e);await ci({pmRoot:e,op:"assurance:gate:verdict",author:G(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:wi,lockWaitMs:vi})}async function mu(e,t={}){let n=t.limit??Ng;if(!Number.isInteger(n)||n<1||n>yn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${yn}`);return(await at(si(e),se)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var Xn={type:"string",minLength:1,maxLength:128,pattern:"\\S"},xi={type:"array",minItems:1,maxItems:Ua,items:Xn},pu={...xi,items:{...Xn,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},oy={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,xi])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:Xn,id:Xn}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:pu}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:xi}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:pu,authors:xi}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Ua,items:{type:"array",minItems:2,maxItems:2,items:Xn}}}}]}}},gT={$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:Qc,items:oy}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function fu(e,t,n,r){let i=await It(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:hu(i,t,n,r)}function sy(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function hu(e,t,n=5,r=!1){let i=[],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=nd(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 S=a.get(_.type)??{items:0,violations:0,missing_fields:0};S.items+=1;for(let k of v)u+=1,S.violations+=1,S.missing_fields+=k.missing_fields.length,k.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:_.id,type:_.type,status:_.status,decision:k});a.set(_.type,S)}let h=r||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:sy(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:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import cy 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 dy(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function yu(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new y("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Policy definition must be an object.",g.USAGE);return t}async function ly(e,t){let n=j(process.cwd(),e.path);await re(n);let r=await $(n);return{pmRoot:n,settings:r,author:G(t,r.author_default)}}function _u(e,t,n,r){if(e==="policy-mode")return za({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let a=Ha(r.definition),o=za({...n,policies:[...i,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
@@ -49,7 +49,7 @@ ${d}`,g.GENERIC_FAILURE)}}function pp(e){let t=e.trim(),n=t.includes("@file:")?t
|
|
|
49
49
|
`,conflict_paths:c,paths_from_theirs:d,preferred:i}}import aa from"node:path";import{execFile as XE}from"node:child_process";import{createHash as Jf}from"node:crypto";import{readdir as ZE}from"node:fs/promises";import QE from"node:path";import{promisify as e0}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 _t=e0(XE),ia=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function lj(e,t,n){let r=t.trim(),i=/^(['"])(.*)\1$/su.exec(r)?.[2]??r;for(let a of["rebase-merge","rebase-apply"])try{let{stdout:o}=await _t("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Jn(o.trim(),128))?.trim();if(s===void 0||!ia.test(s))continue;let{stdout:c}=await _t("git",["rev-parse","--verify",`${s}:${i}`],{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 _t("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!ia.test(o))return;let{stdout:c}=await _t("git",["rev-parse","--verify",`${o}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Jf(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 Vf(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"&&ia.test(t.original_head)&&typeof t.original_blob=="string"&&ia.test(t.original_blob)}async function Kf(e,t,n,r){if(r!==void 0&&Jf(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await _t("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 ZE(i.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await _t("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await _t("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await _t("git",["hash-object","--",QE.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await _t("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 t0=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,n0=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,sa=2048,r0=64,i0=1e5,a0=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 gt(e){return t0.test(e)}var o0=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ca="bounded_non_sensitive_scalars_v1",s0=new Set(["open","in_progress","blocked","closed","canceled"]),c0=new Set(["risk","confidence","severity"]),d0=new Set(["low","medium","high","critical"]),Xf=new Map([["priority",new Set([0,1,2,3,4].map(C))],["status",new Set([...s0].map(C))],...[...c0].map(e=>[e,new Set([...d0].map(C))])]);function nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zf(e,t){return Object.keys(e).every(n=>t.has(n))}function oa(e){return Array.isArray(e)&&e.length<=sa&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function br(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>i0||r.depth>r0)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(nt(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function Qf(e){if(!nt(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[Zf(e,o0),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"),br(e.base),br(e.ours),br(e.theirs),br(e.retained),br(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function l0(e){if(!nt(e))return!1;let t=Object.entries(e);return t.length<=sa&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function u0(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||aa.posix.isAbsolute(e))return!1;let n=aa.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&aa.posix.basename(n,aa.posix.extname(n))===t}function m0(e){return!oa(e.fields_from_theirs)||!oa(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>sa||!e.decisions.every(Qf)?!1:e.merged_field_hashes===void 0||l0(e.merged_field_hashes)}function p0(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[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")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ca)&&i.includes(e.evidence_source)}function f0(e){return typeof e.created_at=="string"&&cn(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&cn(e.reconciled_at))}function Yf(e,t){if(!nt(t)||ua(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||Xf.get(e)?.has(C(r))===!0)&&Pt(r)===t.pm_value_hash}function h0(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&Yf(r.field,r.retained)&&Yf(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(nt(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(nt(i.discarded)&&Object.hasOwn(i.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===ca)}function _0(e){return e.operation!==void 0&&!Vf(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function g0(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||!Zf(e,a0)?"required_fields":typeof e.id!="string"||!gt(e.id)?"receipt_id":typeof e.item_id!="string"||!n0.test(e.item_id)?"item_id":u0(e.item_path,e.item_id)?null:"item_path"}function da(e,t){if(!nt(e))return"required_fields";let n=g0(e);return n!==null?n:_0(e)?m0(e)?p0(e)?f0(e)?t==="durable"&&!h0(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function la(e){if(!nt(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(r=>!nt(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:K(void 0),ours:K(void 0),theirs:K(void 0),...r})}}function eh(e){if(!nt(e))return;if(!oa(e.fields_from_theirs))return"fields_from_theirs";if(!oa(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>sa)return"decisions";let t=e.decisions.findIndex(n=>!Qf(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function Cs(e,t){return da(e,t)===null}function ua(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 Ts(e,t){let n=Rn(t),r=Pt(n?void 0:t);return!n&&(t===null||Xf.get(e)?.has(C(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash: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]="21c15a9e-da38-5fec-9a7d-57556f77ce0a")}catch{}})();var S0=k0(y0),$s=16*1024*1024,ma=100;async function Os(e){try{let{stdout:t}=await S0("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 rh(e,t){let n=fe.dirname(fe.resolve(e,t));for(let r=0;r<12;r+=1){if(await D(fe.join(n,"settings.json")))return n;let i=fe.dirname(n);if(i===n)break;n=i}return null}function pa(e){return fe.join(e,"merge-receipts")}function Nt(e){return`${e}.json`}async function th(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Jn(e.receiptPath,$s)}catch(a){if(kt(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=la(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Cs(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||fe.basename(e.receiptPath)!==Nt(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Sr(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
50
50
|
`}}function kr(e,t=!1){return Ae(C({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:Ae(C(K(n.retained))),discarded_hash:Ae(C(K(n.discarded)))})):fa(e).decisions}))}function Sr(e){let t=[kr(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(kr(e,!0)),t}function E0(e,t){let{reconciled_at:n,settlement:r,...i}=e;return t.state==="reconciled"?{...i,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...i,state:"pending"}}async function x0(e,t,n){let r=new Map;for(let i of t){let a=e.get(i.id);if(i.state!=="reconciled"||a===void 0)continue;let o=r.get(a.item_id);if(o===void 0){try{o=await at(fe.join(n,"history",`${a.item_id}.jsonl`),a.item_id),At(o).ok||(o=[])}catch{o=[]}r.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=C({...fa(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=>C(m)===c)})){let{reconciled_at:d,settlement:l,...u}=a;e.set(a.id,{...u,state:"pending"})}}}function fa(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:ua(t.retained)??Pt(Rn(t.retained)?void 0:t.retained),discarded_hash:ua(t.discarded)??Pt(Rn(t.discarded)?void 0:t.discarded)}))}}async function Pj(e){let t=await Os(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=fe.basename(r,fe.extname(r)),a={version:1,id:w0(),item_path:r.replaceAll("\\","/"),item_id:i,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:K(s.base),ours:K(s.ours),theirs:K(s.theirs),retained:K(s.retained),discarded:K(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:T(),value_availability:"clone_local"};await Fn(t),await ee(fe.join(t,Nt(a.id)),`${JSON.stringify(a,null,2)}
|
|
51
51
|
`);let o=await rh(e.cwd,a.item_path);if(o!==null){let s=pa(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:Ts(u.field,u.retained),discarded:Ts(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:ca};await Fn(s),await ee(fe.join(s,Nt(a.id)),`${JSON.stringify(l,null,2)}
|
|
52
|
-
`)}return a}async function nh(e,t){let n;try{n=await v0(e)}catch(s){let c=await A0(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,a=[],o=(s,c)=>{if(i+=1,a.length>=ma)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},...gt(d)?{receipt_id:d}:{candidate_name_hash:Ae(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await I0(e,s,t);c.receipt!==void 0?r.push(c.receipt):o(s,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:a,invalid_evidence_truncated:i>a.length}}async function A0(e,t,n=b0){if(!U(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!U(i))return!1;let a=fe.dirname(r);if(a===r)return!0;r=a}}async function I0(e,t,n){let r;try{r=await Jn(fe.join(e,t),$s)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=la(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let a=da(i,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:eh(i)}:{}};let o=i;if(t!==Nt(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 R0(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:r}=await import("./indexed-receipt-blobs-QW2VWWJE.js"),i=await r(e,pa(t),n.map(a=>Nt(a.id)),$s);return n.flatMap(a=>{try{let o=la(JSON.parse(i.get(Nt(a.id))??""));if(da(o,"durable")!==null)return[];let s=o,c=Sr(a);return s.id===a.id&&Sr(s).some(d=>c.includes(d))?[a.id]:[]}catch{return[]}})}async function yt(e,t={}){let n=await Os(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await nh(n,"clone_local"),i=t.pmRoot??fe.join(e,".agents","pm"),a=await nh(pa(i),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of r.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?Sr(u):[kr(u)]).includes(kr(m))){o.delete(u.id),s+=1,r.invalid_evidence.length+a.invalid_evidence.length+c.length<ma&&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:E0(u,m))}await x0(o,a.receipts,i);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await R0(e,i,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:r.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...r.invalid_evidence,...a.invalid_evidence,...c].slice(0,ma),invalid_evidence_truncated:r.invalid_evidence_truncated||a.invalid_evidence_truncated||r.invalid_evidence_count+a.invalid_evidence_count+s>ma,clone_local_evidence_resolved:n!==null}}function ih(e,t,n){let r=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),i=[...e].filter(a=>!r.has(a));if(i.length!==0)throw new y(`Merge reconciliation refused ${i.length} receipt(s) without validated tracked evidence; no audit history was written.`,g.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Cn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function Nj(e,t,n={}){let r=await Os(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!Cs(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=T(),o=fe.join(r,Nt(t.id)),s=await rh(e,t.item_path),c=s===null?null:fe.join(pa(s),Nt(t.id)),d=(await Promise.all([th({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[th({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)?[kr(t)]:Sr(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 ee(l.path,l.content)}async function Lj(e){let t=await yt(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 C0}from"node:crypto";import ha from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var T0="2026-08-09T16:15:18.000Z",oh=Symbol("pre-durable-disposition-eligible");function wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ds(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function ah(e){return wt(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 sh(e,t){if(typeof e!="string")return!1;let n=ha.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ha.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ha.posix.basename(n)===`${t}.toon`||ha.posix.basename(n)===`${t}.md`)}function $0(e,t){return typeof e.receipt_id=="string"&>(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&sh(e.item_path,t)}function ch(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,a=Array.isArray(i)?new Set(i.flatMap(o=>ah(o)?[o.field]:[])):new Set;return Ds(t)&&Ds(n)&&Ds(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(ah)&&a.size===i.length&&t.length===a.size&&t.every(o=>a.has(o))}function O0(e,t){return $0(e,t)&&ch(e)}function D0(e,t){return typeof e.receipt_id=="string"&>(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&&sh(e.item_path,t)&&ch(e)}function P0(e){return e[oh]===!0}function dh(e,t){if(!wt(e)||!wt(e.context))return[];let n=e.context.merge;return!wt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!wt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:O0(r,t),[oh]:D0(r,t),...typeof e.ts=="string"&&cn(e.ts)?{eventTimestamp:e.ts}:{}}])}function lh(e,t,n){if(!wt(e)||e.op!=="merge_reconcile")return[];if(!wt(e.context)||!wt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!wt(i)||typeof i.receipt_id!="string"||!gt(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!cn(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function uh(e,t,n=[]){let r=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;r.set(o,Math.max(r.get(o)??0,a.auditHistoryLine))}let i=a=>P0(a)&&a.eventTimestamp!==void 0&&Ht(a.eventTimestamp,T0)<0&&(r.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)&&!i(a)).map(a=>({item_id:a.itemId,history_line:a.line,...gt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:C0("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as N0}from"node:buffer";import{readFile as L0}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 M0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new y("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("History salvage would conceal interior corruption or a malformed record.",g.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(r=>typeof r=="string"))throw new y("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function j0(e){if(Ne(e))throw new y("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[o,s]of e.split(`
|
|
52
|
+
`)}return a}async function nh(e,t){let n;try{n=await v0(e)}catch(s){let c=await A0(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,a=[],o=(s,c)=>{if(i+=1,a.length>=ma)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},...gt(d)?{receipt_id:d}:{candidate_name_hash:Ae(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await I0(e,s,t);c.receipt!==void 0?r.push(c.receipt):o(s,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:a,invalid_evidence_truncated:i>a.length}}async function A0(e,t,n=b0){if(!U(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!U(i))return!1;let a=fe.dirname(r);if(a===r)return!0;r=a}}async function I0(e,t,n){let r;try{r=await Jn(fe.join(e,t),$s)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=la(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let a=da(i,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:eh(i)}:{}};let o=i;if(t!==Nt(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 R0(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:r}=await import("./indexed-receipt-blobs-H2G6CCGO.js"),i=await r(e,pa(t),n.map(a=>Nt(a.id)),$s);return n.flatMap(a=>{try{let o=la(JSON.parse(i.get(Nt(a.id))??""));if(da(o,"durable")!==null)return[];let s=o,c=Sr(a);return s.id===a.id&&Sr(s).some(d=>c.includes(d))?[a.id]:[]}catch{return[]}})}async function yt(e,t={}){let n=await Os(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await nh(n,"clone_local"),i=t.pmRoot??fe.join(e,".agents","pm"),a=await nh(pa(i),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of r.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?Sr(u):[kr(u)]).includes(kr(m))){o.delete(u.id),s+=1,r.invalid_evidence.length+a.invalid_evidence.length+c.length<ma&&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:E0(u,m))}await x0(o,a.receipts,i);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await R0(e,i,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:r.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...r.invalid_evidence,...a.invalid_evidence,...c].slice(0,ma),invalid_evidence_truncated:r.invalid_evidence_truncated||a.invalid_evidence_truncated||r.invalid_evidence_count+a.invalid_evidence_count+s>ma,clone_local_evidence_resolved:n!==null}}function ih(e,t,n){let r=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),i=[...e].filter(a=>!r.has(a));if(i.length!==0)throw new y(`Merge reconciliation refused ${i.length} receipt(s) without validated tracked evidence; no audit history was written.`,g.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Cn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function Nj(e,t,n={}){let r=await Os(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!Cs(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=T(),o=fe.join(r,Nt(t.id)),s=await rh(e,t.item_path),c=s===null?null:fe.join(pa(s),Nt(t.id)),d=(await Promise.all([th({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[th({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)?[kr(t)]:Sr(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 ee(l.path,l.content)}async function Lj(e){let t=await yt(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 C0}from"node:crypto";import ha from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var T0="2026-08-09T16:15:18.000Z",oh=Symbol("pre-durable-disposition-eligible");function wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ds(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function ah(e){return wt(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 sh(e,t){if(typeof e!="string")return!1;let n=ha.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ha.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ha.posix.basename(n)===`${t}.toon`||ha.posix.basename(n)===`${t}.md`)}function $0(e,t){return typeof e.receipt_id=="string"&>(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&sh(e.item_path,t)}function ch(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,a=Array.isArray(i)?new Set(i.flatMap(o=>ah(o)?[o.field]:[])):new Set;return Ds(t)&&Ds(n)&&Ds(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(ah)&&a.size===i.length&&t.length===a.size&&t.every(o=>a.has(o))}function O0(e,t){return $0(e,t)&&ch(e)}function D0(e,t){return typeof e.receipt_id=="string"&>(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&&sh(e.item_path,t)&&ch(e)}function P0(e){return e[oh]===!0}function dh(e,t){if(!wt(e)||!wt(e.context))return[];let n=e.context.merge;return!wt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!wt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:O0(r,t),[oh]:D0(r,t),...typeof e.ts=="string"&&cn(e.ts)?{eventTimestamp:e.ts}:{}}])}function lh(e,t,n){if(!wt(e)||e.op!=="merge_reconcile")return[];if(!wt(e.context)||!wt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!wt(i)||typeof i.receipt_id!="string"||!gt(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!cn(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function uh(e,t,n=[]){let r=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;r.set(o,Math.max(r.get(o)??0,a.auditHistoryLine))}let i=a=>P0(a)&&a.eventTimestamp!==void 0&&Ht(a.eventTimestamp,T0)<0&&(r.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)&&!i(a)).map(a=>({item_id:a.itemId,history_line:a.line,...gt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:C0("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as N0}from"node:buffer";import{readFile as L0}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 M0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new y("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("History salvage would conceal interior corruption or a malformed record.",g.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(r=>typeof r=="string"))throw new y("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function j0(e){if(Ne(e))throw new y("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[o,s]of e.split(`
|
|
53
53
|
`).entries()){if(!s.trim()){n+=s.length+1;continue}let c=M0(s);if(c===null){r===void 0&&(r=n,i=o+1),n+=s.length+1;continue}if(r!==void 0)throw new y("History salvage would discard a record or conceal interior corruption.",g.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=At(t);if(!a.ok||a.item_hash_version===void 0)throw new y("History salvage requires a nonempty verified prefix.",g.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:r===void 0?e:e.slice(0,r),receipt:r===void 0?null:{first_invalid_line:i,discarded_bytes:Buffer.byteLength(e.slice(r)),discarded_sha256:Ae(e.slice(r)),retained_entries:t.length}}}async function F0(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await El(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function mh(e){let t;try{t=await L0(e)}catch(n){if(U(n))return null;throw n}if(!N0(t))throw new y("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function ph(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new y("Tail salvage cannot be combined with other repair modes.",g.USAGE);let a=await mh(t.historyPath);if(a===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await Ue({path:t.historyPath,scope:"project"});let o=j0(a),s=_l(o.entries,o.entries.length-1),c=Qd(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new y("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let d=await F0(t,n,c),l=Co({itemDocument:d.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=o.itemHashVersion,m=r.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await oe(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await mh(t.historyPath),_=await we(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=_?await V(_.itemPath):null;if(h!==a||w!==d.itemRaw)throw new y("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=ni({...Xd({hashAlgorithm:Re(o.entries.at(-1).hash_algorithm),nowIso:T(),author:i,op:"history_salvage",before:c,after:c,message:r.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 Oi({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
|
|
54
54
|
`}),l.push(...await Y({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 yh}from"node:fs/promises";import Ps from"node:path";import wh 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 fh(e,t){return t==="body"?e.body:e.metadata[t]}function U0(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function H0(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 hh(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>U0(e,r)))return t;let n=t.map(r=>e==="comments"?r:H0(r));return[...new Map(n.map(r=>[C(r),r])).values()]}function Ns(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let a=t.findIndex((o,s)=>!r.has(s)&&Ns(i,o));return a<0?!1:(r.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(([r,i])=>Object.hasOwn(n,r)&&Ns(i,n[r]))}function _h(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let a=e[i],o=new Set;for(let c of ai(a.patch))o.add(pi(c.path)),c.from&&o.add(pi(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function z0(e,t,n){let r=wh.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(pi(p.path));let a=new Set([...i].filter(p=>Ns(hh(p,fh(t,p)),hh(p,fh(n,p))))),o=new Set([...i].filter(p=>!a.has(p))),s=_h(e,o),c=_h(e,a),d=[...i].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:i.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 W0(e){try{return await yh(e)}catch{return null}}async function q0(e){if(await W0(Ps.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 r=Object.keys(n).sort();if(t.length!==r.length||t.some((a,o)=>a!==r[o]))return null;let i=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:i[a];return[Pt(o),Ae(C(K(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function G0(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 yh(e.itemPath),r=[];for(let o of t){let s=await q0({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&r.push(s)}let i=new Set(r.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return r.length>0&&(a===void 0||a.length>0&&a.every(o=>i.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function gh(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:Ps.relative(a,t.currentItemPath).split(Ps.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==i.item_path||i.operation===void 0||!await Kf(a,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new y("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function B0(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 yt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,r=n?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[];ih(t,n,e.options.dryRun===!0);let i=e.options.mergeReceiptProof?await G0({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.reason}).`,g.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=i?.trusted?r.filter(o=>i.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:a.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:a.map(fa)}}:e.options.auditContext}}function J0(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,a=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=ii(i.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:r,matchedChainBefore:ln(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:i.raw,loadedItem:i}}function V0(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 K0(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=Re(e.reanchorEntries.at(-1)?.hash_algorithm),i=ln(e.finalReplay,e.itemHashVersion,r),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=i.indexOf(a),s=ln(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?wh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[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(ni({...c,event_class:Bd(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function Y0(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Ls(e,t,n){let{pmRoot:r,settings:i,typeRegistry:a}=await lo(n.path),o=await Gl(r,e,i,a.type_to_folder);return t.salvageTail===!0?ph({pmRoot:r,subject:o,settings:i,typeRegistry:a,options:t,author:G(t.author,i.author_default)}):tm({pmRoot:r,subject:o,settings:i,typeRegistry:a,operation:"history-repair",options:t,transform:s=>Z0({pmRoot:r,subject:o,options:t},s)})}function X0(e,t,n){let r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(i=>i.record_hash_version!==void 0&&i.op==="merge_reconcile"&&C(i.context)===C(n));return e.forceAuditEntry===!0&&!r}async function Z0(e,t){let{pmRoot:n,subject:r,options:i}=e,a=t.entries,o=t.verification,s=At(a),c=i.normalizeProvenance?Ku(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=el(c.entries),l=new Set(c.entries.map(A=>A.item_hash_version).filter(A=>A!==void 0)),u=oi(c.entries,d),m=J0(r,t,d);await gh(i.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=ln(f,d),h=!1;if(m.currentItemReplay!==null){let A=ln(m.currentItemReplay,d);h=!p.some((R,X)=>R===A[X])}let _=h&&m.currentItemReplay?z0(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await B0({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:_}),S=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,X0(i,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,x=!!i.dryRun,O=V0({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:E,auditEntryAdded:b}=K0({reanchorEntries:u.entries,changed:S,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:O,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),N=Y0(S,u.skippedOps,_);return{changed:S,rewrittenEntries:E,beforeWrite:async()=>gh(i.mergeAbandonmentProof,m,o.ok,u),report:({verification:A,warnings:R})=>({id:r.id,dry_run:x,changed:S,history:{path:r.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:A.ok,verify_errors:A.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:i.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...N,...R])].sort((X,xe)=>X.localeCompare(xe)),generated_at:T()})}}function CF(e,t){if(t&&e!==void 0)throw new y("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new y("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function TF(e,t){if(e.salvageTail===!0)throw new y("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await lo(t.path),a=[],o=await st(n,r.item_format,i.type_to_folder,a,r.schema,{forceSourceScan:!0}),s=await Jt(n,o),c=e.normalizeProvenance?await Yu(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 Ls(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 Jd(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]="688b552b-3d10-521e-b695-b3edfbfed36e")}catch{}})();var Q0=new Set(Ml),vh=25,ex=ke.join("runtime","telemetry","events.jsonl"),tx=ke.join("runtime","telemetry","state.json"),nx=2500,rx=500,bh=Hl-3,ix=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function zs(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||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 Ws(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Tn(e){return e.trim().toLowerCase()}function Fs(e,t){let n=Tn(e),r=Tn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function qs(e){try{return(await vt.stat(e)).isDirectory()}catch{return!1}}async function ax(e){let t=(await vt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>vt.readdir(ke.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Un.some(a=>i.name.endsWith(a))).map(i=>ke.parse(i.name).name)))}async function ox(e,t,n,r){let i=await Ue({path:e,scope:"project"}),a=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!a)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await vt.readFile(e,"utf8")}catch{return{warnings:i,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:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function sx(e,t,n){let r=ke.join(e,"history");if(!await qs(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await vt.readdir(r)).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 i){let u=ke.join(r,l),m=l.slice(0,-6),f=await ox(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:i.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 Us(e,t){return ke.relative(e,t).replaceAll("\\","/")}async function kh(e,t){let n=[...new Set(Object.values(t))].sort((i,a)=>i.localeCompare(a)),r=[];for(let i of n){let a=ke.join(e,i),o=[];try{o=await vt.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&U(s))continue;continue}for(let s of o)Un.some(c=>s.toLowerCase().endsWith(c))&&r.push(ke.join(a,s))}return r.sort((i,a)=>Us(e,i).localeCompare(Us(e,a))),r}function cx(e){return!(typeof e=="object"&&e!==null&&"code"in e&&U(e))}async function dx(e,t,n){let r=await kh(e,t),i=[],a=[],o=[],s=[],c=en(H());for(let d of r){let l=Us(e,d),u;try{u=await vt.readFile(d,"utf8")}catch{i.push(l);continue}let m=Ne(u);if(m){a.push({path:l,...m});continue}try{let f=xt(u,{format:Yc(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:Zr(f.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function lx(e){let t=ke.join(e,"history"),n=[],r=[],i=[],a=[],o=[],s=[];try{s=(await vt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){cx(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await vt.readFile(ke.join(t,c),"utf8")}catch{n.push(d);continue}let u=Ne(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...dh(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...lh(p,d,f+1))}catch{i.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function Sh(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 ux(e,t,n,r,i,a){let o=await dx(e,t,n),s=await lx(e),c=Qr(o.formatVersions,Hn,Xr),d=_e(n),l=yi(a,A=>zd(A,d),Bn()),u=await na(e),m=await Rt(e),f=await Lf(e,m,r,i),p=m===null?null:await _n(m),h=await yt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),_=new Set(h.durable_receipt_ids),w=uh(s.mergeReceiptReferences,_,s.mergeReceiptDispositions),v=w.missing,S=h.receipts.filter(A=>A.state==="pending"),{pendingDecisions:k,lossless:x}=Cn(S),O=p?.status==="missing"&&p.missing_keys.length===5&&p.drifted_keys.length===0,E=[...o.unreadable.map(A=>`integrity_item_unreadable:${A}`),...o.conflictMarkers.map(A=>`integrity_item_conflict_marker:${A.path}:L${A.line}`),...o.parseFailures.map(A=>`integrity_item_parse_failed:${A}`),...s.unreadable.map(A=>`integrity_history_unreadable:${A}`),...s.conflictMarkers.map(A=>`integrity_history_conflict_marker:${A.id}:L${A.line}`),...s.invalidJson.map(A=>`integrity_history_invalid_json:${A.id}:L${A.line}`),...c.outdated.map(A=>`integrity_item_outdated_format_version:${A}`),...c.ahead.map(A=>`integrity_item_ahead_format_version:${A}`),...Sh(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...p!==null&&p.status!=="ok"?[`merge_driver_configuration_${O?"missing":"drift"}:${p.missing_keys.length+p.drifted_keys.length}`]:[],...f.warnings,...k.length>0?[`merge_decisions_unreviewed:${k.length}`]:[],...x.length>0?[`merge_receipts_pending:${x.length}`]:[],...Mf({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:v.length})],b=[...new Set(E)].sort((A,R)=>A.localeCompare(R)),N=b.filter(A=>!A.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:N.length===0?"ok":"warn",ok:N.length===0,details:{checked_item_files:o.paths.length,checked_history_streams: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:p===null||p.status==="ok"?0:p.missing_keys.length+p.drifted_keys.length,merge_fence:f.count,pending_merge_decisions:k.length,lossless_merge_receipts:x.length,invalid_merge_receipt_evidence:h.invalid_evidence_count,missing_merge_receipt_history_references:v.length,accepted_legacy_merge_receipt_references:w.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:w.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:ze(l.relations,rm)},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:p===null?null:{...p,required:i},merge_fence:f.audit,pending_merge_decision_items:[...new Set(k.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),lossless_merge_receipt_items:[...new Set(x.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),invalid_merge_receipt_evidence_details:h.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:h.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:v.slice(0,To),missing_merge_receipt_history_reference_details_truncated:v.length>To}},warnings:b,gitWorkspaceRoot:m,pendingMergeReceipts:S}}function mx(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function px(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:mx(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function fx(e,t){return Z(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function hx(e){let t=Z(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function _x(e){return Z(e.reason)??Z(e.error)??Z(e.message)}function Ms(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function gx(e){let t=[],n=[],r=[];e.forEach((a,o)=>{let s=fx(a.definition,o),c=hx(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){r.push({layer:a.layer,name:a.name,id:s,status:c,reason:_x(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Ms),n.sort(Ms),r.sort(Ms);let i=[...r.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:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Eh(e,t,n,r,i,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>Ws(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=ds(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."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>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: ${Lr.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:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,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 yx(e,t,n){let r=await _s(Ve(e)),i=await Ke({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=i.loaded.map(E=>px(E)),o=await Ju(i.loaded,Ve(e)),s=await Ye({...i,loaded:i.loaded}),[c,d]=await Promise.all([ge(i.roots.project),ge(i.roots.global)]);await hs(e,s.registrations.migrations);let l=gx(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(E=>Tn(E.name))),f=new Set(d.state.entries.map(E=>Tn(E.name))),p=[...new Map(i.loaded.filter(E=>!(E.layer==="project"?m:f).has(Tn(E.name))).map(E=>[`${E.layer}:${E.name}`,{layer:E.layer,name:E.name,directory:E.directory}])).values()].sort((E,b)=>{let N=`${E.layer}:${E.name}`,A=`${b.layer}:${b.name}`;return N.localeCompare(A)}),h=p.map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),_=p.filter(E=>Fs(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),w=p.filter(E=>!Fs(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],S=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=_r(S),x=gr(),O=Eh(S,i.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:S.length===0?"ok":"warn",ok:S.length===0,details:{...i,loaded:a,warnings:S,activation:u,author_manifest:r,triage:O,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:k,host_version_census:o}},warnings:S}}function Hs(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=im(e,vh);return{values:n.values,truncated:n.truncated,total:e.length}}function _a(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function wx(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return Q0.has(e)?e:null}function ga(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 xh(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e.split(`
|
|
55
55
|
`)){let s=o.trim();if(s.length!==0){r+=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>=bh&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:a}}function vx(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function bx(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 kx(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||co().telemetry_disabled?void 0:{attempted:!0,...await Ah(n)}}function Sx(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!i||a>i),s=!i,c=t.validEntries>=rx;return(o||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function Ex(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function xx(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Ul?[`telemetry_schema_version_behind:${t}`]:[]}function Ax(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function Ix(){return{...co(),pm_no_telemetry:_a("PM_NO_TELEMETRY"),telemetry_otel_disabled:_a("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:_a("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:wx()}}function Rx(e,t){return e.telemetry.enabled&&t.validEntries>0}function Cx(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Ah(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(nx)});return{probe_url:ga(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of ix){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:ga(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Tx(e,t){let n=Fr(process.cwd()),r=ke.join(n,ex),i=ke.join(n,tx),a=await V(r),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?xh(a):vx(),d=await V(i),{runtimeState:l,stateParseFailed:u}=bx(d),m=e.telemetry.endpoint.trim(),f=ga(m),p=await kx(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...Sx(e,c,l),...Ex(p),...xx(p),...Ax(e,l));let _=Rx(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:r,queue_exists:o,queue_entries:c.validEntries,queue_draining:Cx(_,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:bh,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:Ix()}},warnings:h}}async function $x(e){let t;try{t=await xm(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function Ox(e){let t="metadata",n=e.items,r=await Jt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(i.length>0){n=await st(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Jt(e.pmRoot,n),a=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,S)=>v.localeCompare(S));let w=new Set(a);o=i.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=r,_=[...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:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:i.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 Dx(e,t){let n=fi(e),r=Gn(n.settings),i=gi(n.settings,t),a=r.active?Wt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(r.active&&i.active)}}function Px(){return{refreshed:[],skipped:[],warnings:[]}}async function Nx(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Px():Ll(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function Lx(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&mn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function Mx(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function jx(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,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:ao(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:ao(r,e.vector_store?.adapter??null)}}function Fx(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function Ux(e,t,n){return e.enabled&&n.length>0&&t}async function Hx(e,t,n,r,i){let a=Dx(t,e),o=await pn(e),s=a.semanticRuntimeAvailable?uo(n,o.entries):[],c=await Nx({pmRoot:e,snapshot:a,refreshPolicy:r,staleBefore:s}),d=await pn(e),l=a.semanticRuntimeAvailable?uo(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=Lx({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=Mx({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Hs(s,i),h=Hs(l,i),_=Ux(r,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:Fx(r),...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:i?"full":"summary",stale_items_summary_limit:vh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:jx(r,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 zx(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 y("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var Wx=new Set(["extensions","locks","search"]);function qx(e){let t=new Set(Fc.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Uc));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of Wx)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,a)=>i.localeCompare(a)),optionalDirs:[...n].sort((i,a)=>i.localeCompare(a)),optionalDirSet:n}}async function Gx(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:a}=qx(t),o=[],s=[],c=[];for(let d of[...r,...i]){let l=ke.join(e,d);c.push(...await Ue({path:l,scope:"project"})),!await qs(l)&&(a.has(d)?s.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function Ch(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function Bx(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?ot(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):st(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function js(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function Jx(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 Vx(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 Kx(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 Gs=e=>e.unknown_event_count??0,Bs=e=>e.actionable_unknown_event_count??Gs(e);function Yx(e,t,n,r,i,a){let o=Gs(r),s=Bs(r),c=o>0,d=s>0,l=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:r}:{},...l?{stale_in_progress:i}:{},...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 Th(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Xx(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 Zx(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Qx(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 $h(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let a of i)t.has(a)||t.set(a,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",a=jo(r)?.code??Ws(r),o=n.get(i)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=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=zs(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:a,check:i,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function eA(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 tA(e){for(let t of e.checks){let n=Fo(e.remediationSources[t.name]);eA({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function nA(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){let s=i.get(o.item_id)??[];s.push(o),i.set(o.item_id,s)}let a=[];for(let o of n){if(r.has(o))continue;let s=i.get(o);if(!(!s||s.length===0))try{await Ls(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 rA(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function Oh(e,t={}){let n=j(process.cwd(),e.path);await re(n);let r=jt(n),{settings:i,warnings:a}=await rl(n),o=[...new Set(a)],s=W(i,H()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Rh(t),m=await Gx(n,s,c),f=zx(i),p=await Tx(i,{checkTelemetry:t.checkTelemetry===!0}),h=await yx(n,i,!!e.noExtensions),_=Ch(t),w=[],v=await Bx({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),S=v,k=Di(_e(i.schema),v),x=[...(await fm({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(me=>me.startsWith("agent_guidance_")),...f,...Pi(k)],O=_.skipDrift?{warnings:[]}:await pl({pmRoot:n,settings:i,itemIds:v.map(me=>me.id),commandLabel:"health"}),E=await sx(n,i.history.compact_policy,await ax(n)),b=await er(n,20,t.verboseAuthorEvents===!0),N=Bs(b),A=N>0?[`history_unknown_author_events:${N}`]:[],R=Th(await jl(n,v,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),X=await Qu(n),xe=X.warnings,ye=await $x(n),he=_.skipIntegrity&&!l?{...js("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await ux(n,s.type_to_folder,i.schema,i,l,v),Fe=_.skipDrift?js("history_drift"):await Ox({pmRoot:n,items:S,settings:i,typeRegistry:s,itemReadWarnings:w}),Dr=[...new Set(w)],jn=await nA({gitWorkspaceRoot:he.gitWorkspaceRoot,pendingMergeReceipts:he.pendingMergeReceipts,historyDriftCheck:Fe,global:e});rA(Fe,jn);let z=_.skipVectors?js("vectorization"):await Hx(n,i,S,u,t.verboseStaleItems===!0),B=[Jx(r,i,o),Vx(m,c),Kx(x,k),p.check,h.check,Yx(v,i,E,b,R.scan,X),ye.check,he.check,Fe.check,z.check],Pr=Xx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Dr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:O.warnings,historySummary:E,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:xe,locksCheck:ye,integrityCheck:he,historyDriftCheck:Fe,vectorizationCheck:z}),Nr=Qx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Dr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:O.warnings,historySummary:E,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:xe,locksCheck:ye,integrityCheck:he,historyDriftCheck:Fe,vectorizationCheck:z});tA({checks:B,remediationSources:Nr,historyDriftedCount:Zx(Fe),overThresholdCount:E.over_threshold.length});let La=Pr.filter(me=>!zs(me,l)),Ma=$h({warnings:Pr,checks:B,remediationSources:Nr,requireMergeDrivers:l}),Rg=new Set(Ma.filter(me=>me.severity==="gate_failing").map(me=>me.check)),Cg=new Set(Ma.map(me=>me.check));for(let me of B)me.ok=!Rg.has(me.name),Cg.has(me.name)&&(me.status="warn");let Tg={ok:La.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&La.length>0?g.GENERIC_FAILURE:0},checks:B,warnings:Pr,findings:Ma,failed_because:La,generated_at:T()};return Do(Tg,t,_.summaryMode)}var C1={buildHierarchyIntegrityWarnings:Sh,buildExtensionHealthTriageSummary:Eh,buildHealthFindings:$h,buildCapabilityContractMetadata:gr,buildStaleInProgressHealthSummary:Th,buildVectorizationProviderDetails:Ih,collectUnknownCapabilityGuidance:_r,isAdvisoryHealthWarning:zs,isDirectory:qs,isExpectedUnmanagedExtension:Fs,listItemDocumentPaths:kh,normalizeEndpointForDisplay:ga,normalizeExtensionNameForMatch:Tn,parseTelemetryQueue:xh,probeTelemetryEndpointHealth:Ah,projectHealthResult:Do,resolveActionableUnknownAuthorEventCount:Bs,resolveHealthSkipPolicy:Ch,resolveUnknownAuthorEventCount:Gs,resolveVectorRefreshPolicy:Rh,selectStaleItemDetail:Hs,summarizeHealthCheckDetails:$o,summarizeExtensionList:nr,summarizeRecordList:ze,summarizeStringList:q,telemetryEnvFlagEnabled:_a,warningCode:Ws};(function(){try{var e=typeof window<"u"?window:typeof 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(!Bl(e,t).ok)return{reason:"unverified_history"};let r=ri(),i={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(r.metadata.status));r=hl(r,o.patch,a+1,o.op),n.has(String(r.metadata.status))?s||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&Et(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function Ph(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function Nh(e,t,n,r,i){let a=Ph(n),o=t.filter(d=>a.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of r?o:[]){let l;try{let u=await at(Ft(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,i).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function Lh(e,t){let n=j(process.cwd(),t.path),r=await $(n),i=_e(r.schema);await ct({pmRoot:n,settings:r,id:e.item_id,op:"update",author:G(t.author,r.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 at(Ft(n,a.metadata.id),a.metadata.id),s=Ph(i),c=Dh(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new y("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",g.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 iA(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Mh(e){return`${e.item_id} ${e.link_kind}`}function jh(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=iA(i.classification,r.classification),i.owners.set(Mh(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Mh(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.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 Fh(e,t,n,r,i=40){let a=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):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=jh(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=ei(f.status,r)??f.status;r.terminal_statuses.has(p)?(u.push(f),p===r.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,a),items_truncated:d.items.length>a}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import $n from"node:fs/promises";import On from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function aA(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await $n.readdir(On.join(e,i))}catch{return}for(let o of a)for(let s of Un)if(o.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-s.length)});break}})),r.sort((i,a)=>i.relativePath.localeCompare(a.relativePath))}function oA(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,o=Ne(t);if(o){a.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=sA(e,t);s!==null&&(s.op==="delete"&&i.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 sA(e,t){let{id:n,relativePath:r,out:i}=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 i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return a}function Js(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 cA(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await $n.readdir(On.join(e,"history"))}catch{return n}for(let i of r.sort((a,o)=>a.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await $n.readFile(On.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Js("history stream",o)});continue}oA({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function Uh(e){let t=Ne(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 dA(e){let t=[],n=0,r=null;try{r=await V(jt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Js("configuration file",a)})}if(r!==null){n+=1;let a=Uh(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await $n.readdir(On.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of i.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await $n.readFile(On.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Js("configuration file",c)});continue}let s=Uh(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function Hh(e,t,n,r={}){let i=await aA(e,n),a=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){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(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=On.join(e,u.relativePath);return xt(await $n.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await cA(e,a),l=await dA(e);return{item_files_on_disk:i.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 vc from"node:fs/promises";import{realpathSync as SI}from"node:fs";import{execFile as EI}from"node:child_process";import Ee from"node:path";import{promisify as xI}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 lA=["metadata","resolution"],Vs=["metadata","resolution","estimates","timestamps","lifecycle"],uA="completed";function Ks(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function zh(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 r=zh(n.close_reason)??uA;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Ks(r)}`,gate:"resolution"})}return t}function qh(e){let t=[];for(let n of e){let r=zh(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Ks(r)}`,gate:"metadata"})}return t}function Gh(e,t){return e.map(n=>{let r=nl(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function Bh(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 Jh(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Ks(n.path)}`})}return t}function Vh(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new y(`--fix-scope values must not be empty. Supported values: ${Vs.join(", ")}.`,g.USAGE);return new Set(lA)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Vs.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${Vs.join(", ")}.`,g.USAGE)}return n}function Kh(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Er(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 mA=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function pA(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=mA.exec(n);if(!r)return null;let i=r[1],a=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${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 Yh(e){return typeof e=="string"&&e.trim().length>0}function fA(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,r=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=r.get(d)??[];l.push(s),r.set(d,l)}}let i=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<i.length;o+=1)for(let s of r.get(i[o])??[]){let c=n.get(s);c.delete(i[o]),c.size===0&&(a.add(s),i.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function Xh(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||Yh(i.duplicate_of))continue;let a=pA(i.title,{...t,evidenceText:i.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===i.id)||o.push({id:i.id,title:i.title,parent:Yh(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==i.id.toLowerCase())})}let r=[];for(let[i,a]of n){if(a.length<2)continue;let o=fA(a);if(o.length<2)continue;let s=[...o].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return r.sort((i,a)=>i.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 Zh(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,a)=>i.localeCompare(a))){let i=t.get(r),a={};for(let o of[...i.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=i.get(o);n[r]=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 Qh(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function e_(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let a of t){let o=Qh(a);if(o.length===0)continue;let s=i.get(o);s?s.push(a):i.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=(i.get(Qh(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,r),candidates_truncated:o.length>r}})}function t_(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 hA=/^[a-z][a-z0-9+.-]+:\/\//i;function xr(e){return hA.test(e.trim())}import _A from"node:fs/promises";import Se from"node:path";import{glob as gA}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 yA=["path","scope","note"],wA=["pattern","glob","path","scope","note"],vA=["path"],bA=["from","to"],kA=new Set(["note","scope"]);function r_(e){let t=e??"project";if(!ja.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${ja.join(", ")} (default: project).`,g.USAGE);return t}function Ys(e){if(e.startsWith("```")||e.includes(`
|
|
@@ -62,4 +62,4 @@ ${a}`,g.GENERIC_FAILURE)}}function Na(e){return typeof e.tag=="string"&&e.tag.tr
|
|
|
62
62
|
`);ce(e.progressEnabled,"writing keyword artifacts"),await ee(t,`${JSON.stringify(e.manifest,null,2)}
|
|
63
63
|
`),await ee(n,`${i}
|
|
64
64
|
`);let a=[];if(e.mode!=="keyword")try{ce(e.progressEnabled,"writing vectorization status ledger"),await Nl(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 Dq(e,t){let n=LC(e.mode),r=NC(e),i=e.full===!0;ce(r,`start mode=${n}`);let a=j(process.cwd(),t.path);await re(a);let o=fi(await $(a)).settings,s=null;try{s=await oe(a,fl,o.locks.ttl_seconds,G(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===g.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.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=FC(o),d=UC(o),l=BC({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ce(r,"loading item corpus");let m=await JC({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;ce(r,`loaded_items=${h.length}`);let _=T(),w=GC(u,_,h),v=Or.join(a,$c),S=Or.join(a,Oc),k=u==="keyword"?await Pc(a,p,o.schema,f):h,x=[],O={},E=null,b=qC(u);if(u==="keyword"&&await VC({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let R=await tT({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:k,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:x,semanticSummary:b,progressEnabled:r});k=R.documentsForKeywordArtifacts,O=R.vectorizationLedgerEntries,E=R.vectorizationEmbeddingMetadata}let N=await nT({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:O,vectorizationEmbeddingMetadata:E,progressEnabled:r}),A=[...await Y({path:v,scope:"project",op:"reindex:manifest"}),...await Y({path:S,scope:"project",op:"reindex:embeddings"}),...await Br({mode:u,total_items:h.length})];return ce(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:$c,embeddings:Oc},warnings:[...f,...x,...N,...A],generated_at:_}}finally{await s?.()}}export{L as a,Ce as b,Ze as c,gn as d,Yl as e,Zl as f,qt as g,mo as h,jg as i,ho as j,_o as k,nu as l,wn as m,Kn as n,yo as o,ry as p,cu as q,Yn as r,wo as s,Ei as t,vo as u,lu as v,uu as w,mu as x,Mm as y,oy as z,gT as A,hu as B,dy as C,MT as D,Uv as E,aP as F,cP as G,dP as H,sr as I,lP as J,uP as K,mP as L,pP as M,fP as N,hP as O,_P as P,gP as Q,yP as R,wP as S,vP as T,ms as U,vs as V,NO as W,fm as X,py as Y,Ri as Z,y$ as _,P as $,ie as aa,w$ as ba,So as ca,v$ as da,b$ as ea,Au as fa,k$ as ga,S$ as ha,E$ as ia,Ry as ja,x$ as ka,A$ as la,Eo as ma,I$ as na,R$ as oa,ko as pa,C$ as qa,T$ as ra,Ru as sa,$$ as ta,Ty as ua,$u as va,H$ as wa,er as xa,z$ as ya,My as za,jy as Aa,W$ as Ba,Fy as Ca,i_ as Da,V$ as Ea,ju as Fa,o_ as Ga,WU as Ha,qU as Ia,tr as Ja,$i as Ka,Uu as La,Hu as Ma,zu as Na,Wu as Oa,Ju as Pa,Ku as Qa,Yu as Ra,Qu as Sa,Pt as Ta,QM as Ua,ej as Va,tj as Wa,nj as Xa,lj as Ya,Kf as Za,fa as _a,Pj as $a,yt as ab,ih as bb,Nj as cb,Lj as db,T0 as eb,P0 as fb,dh as gb,aw as hb,tm as ib,Ls as jb,CF as kb,TF as lb,Di as mb,Pi as nb,Oh as ob,C1 as pb,Dh as qb,Nh as rb,Lh as sb,Fh as tb,Hh as ub,QA as vb,eI as wb,VU as xb,KU as yb,YU as zb,XU as Ab,nI as Bb,rI as Cb,iI as Db,ZU as Eb,d_ as Fb,oI as Gb,l_ as Hb,nc as Ib,m_ as Jb,sI as Kb,cI as Lb,dI as Mb,p_ as Nb,rc as Ob,iH as Pb,aH as Qb,sc as Rb,cc as Sb,_H as Tb,gH as Ub,yH as Vb,HI as Wb,Cz as Xb,eg as Yb,Cr as Zb,rg as _b,ig as $b,ag as ac,Sc as bc,KR as cc,uW as dc,PW as ec,zW as fc,gg as gc,yg as hc,wg as ic,mq as jc,xq as kc,Aq as lc,Iq as mc,Dq as nc};
|
|
65
|
-
//# sourceMappingURL=chunk-
|
|
65
|
+
//# sourceMappingURL=chunk-6IU7BESB.js.map
|