@unbrained/pm-cli 2026.10.27 → 2026.10.28
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 +23 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2J7I54MQ.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-25MTQAHX.js → chunk-3KMYHYJV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UHKN6TJM.js → chunk-7V37RC2L.js} +44 -44
- package/dist/cli-bundle/chunks/{chunk-5PTMQBKJ.js → chunk-AHVN4GHF.js} +30 -29
- package/dist/cli-bundle/chunks/{chunk-QQYLNHZK.js → chunk-CS7QDSUX.js} +28 -28
- package/dist/cli-bundle/chunks/{chunk-34OQP43K.js → chunk-CXUQEZDX.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-X5TMR7KC.js → chunk-D3AIQZXF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NNIYQHYT.js → chunk-D6P6IBPN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HIX2OMEZ.js → chunk-DKLEDWVW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2XUDAQK5.js → chunk-DM3PICGU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-32QK43XG.js → chunk-E5QBZ4HI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-H434DKYU.js → chunk-JESLOJD7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-57YPOOED.js → chunk-LWW4F4G2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O3LPT34G.js → chunk-PQLRKFPZ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-ONC4BBQP.js → chunk-RZQNFHXO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ER7RLJW5.js → chunk-TH5KPAN4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-F26MRQZY.js → chunk-XHONSCLJ.js} +6 -6
- package/dist/cli-bundle/chunks/{chunk-EKV5GP6P.js → chunk-YUBUNECD.js} +42 -42
- package/dist/cli-bundle/chunks/{chunk-OQOEBWHU.js → chunk-YYD5MNAV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q55KZDNF.js → chunk-ZX3XMTZG.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-63WYG2PY.js → indexed-receipt-blobs-LHLE7PSG.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-L3A6FSZ7.js → mutation-admission-GKDKHRTZ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-YSQ7UTFI.js → register-list-query-MHJJUM6M.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-6HRXYASW.js → register-mutation-SN425O3R.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-4O3YOYXF.js → register-operations-EYUIUGPW.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-3WAXNDMY.js → register-setup-WUZ2ZSMY.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-CRW6PVQK.js → settlement-hook-MN3Y7LVX.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-I46WD4EN.js → stage-2FYJGGG3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZA6AEYIM.js → chunk-46WLWK73.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-E5C24MCV.js → chunk-4GN2ZPT5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NLZUI234.js → chunk-6L4KKRK7.js} +18 -18
- package/dist/cli-bundle/focused-chunks/{chunk-WDKZB3V6.js → chunk-6VDRAJYX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KTXU5WU6.js → chunk-7SZPZOIC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YQKLKRMW.js → chunk-B4ZQJEMT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-J67PFM3O.js → chunk-BZSACRVX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-Y57A4ZDI.js → chunk-C2GLO7HU.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-R2MTHS2H.js → chunk-DRN4W3YJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TAFMNTA5.js → chunk-F6UQJJYB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TGUOEOKP.js → chunk-I4X6AKOO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SM2KGD4J.js → chunk-IQKLJFJE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XK3XMZM4.js → chunk-JTCGDODH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HWD63G54.js → chunk-L5GX2FGZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MVY6JDIH.js → chunk-LPWZERVD.js} +11 -11
- package/dist/cli-bundle/focused-chunks/{chunk-YW5GHQN2.js → chunk-ML5JIUM6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YC6NCPLK.js → chunk-OASYSUOH.js} +16 -16
- package/dist/cli-bundle/focused-chunks/{chunk-BH7RE2ZY.js → chunk-ON5WFDCG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4TXZBGOR.js → chunk-QUPGBO2L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SYL73MEI.js → chunk-R3EA3SDW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-B266DDBJ.js → chunk-TUN4M757.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZH7GTEWL.js → chunk-Z26ZPQH6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-GAFC52LQ.js → indexed-receipt-blobs-5H6RMRTK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-ENBFMV2X.js → mutation-admission-TM3SVU2O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-PUYJJDFL.js → settlement-hook-LBVWWSCF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-MAWZTM2H.js → stage-7ZBRX2Q2.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 +1 -1
- package/dist/cli-bundle/sdk-core.js +25 -24
- 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 +46 -46
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/item/priority.js +1 -1
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +5 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/command-line.d.ts +6 -0
- package/dist/sdk/command-line.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/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/history.d.ts +4 -0
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/command-resolution.d.ts +5 -0
- package/dist/sdk/test/command-resolution.js +3 -0
- package/dist/sdk/test/execution.js +2 -2
- package/docs/COMMANDS.md +28 -1
- package/docs/SDK.md +40 -0
- package/docs/TESTING.md +28 -2
- 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-XERBUA6A.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-U4UBQBS7.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as Et,d as sn,e as cn,f as dn,g as Tl,j as Dl}from"./chunk-SYL73MEI.js";import{a as Cl}from"./chunk-BH7RE2ZY.js";import{d as Q,h as Ya,s as El}from"./chunk-HWD63G54.js";import{a as Na,c as Ui,d as Hi,e as Vc,g as Kc,h as ja,i as Yc,j as Kt,k as Yt,l as Xc,m as Zc,n as Fa,o as td,p as Xt,q as Zt,r as nd,s as id,t as Ua}from"./chunk-YQKLKRMW.js";import{a as za}from"./chunk-SVOOGGAK.js";import{B as hd,C as Bi,D as _d,E as Ha,G as gd,H as yd,J as wd,K as vd,L as Ji,U as Vi}from"./chunk-ZH7GTEWL.js";import{K as $l}from"./chunk-TGUOEOKP.js";import{A as Al,I as Za,w as Il,y as Xa,z as Rl}from"./chunk-TAFMNTA5.js";import{$ as ur,Aa as Ka,C as Sd,G as xd,H as Id,I as Rd,L as sr,Na as wl,Oa as vl,Sa as bl,Ta as kl,aa as Kd,ba as Ba,ca as qn,ea as Ja,i as Ki,ia as sl,ja as cl,ka as dl,la as ll,m as Fn,ma as fr,n as bd,o as kd,oa as ul,p as Un,pa as ml,qa as pl,ra as Mt,sa as fl,ta as an,ua as hl,va as Va,wa as on,x as Ed,xa as _l,ya as gl,za as yl}from"./chunk-YC6NCPLK.js";import{a as qc,b as Vt,c as Ma,d as Gc,e as Bc,f as tt,g as zi,h as Jc,i as yt}from"./chunk-E5C24MCV.js";import{m as Gn,o as hr,v as Sl,y as xl}from"./chunk-WDKZB3V6.js";import{B as mr,D as rl,E as ge,F as ye,G as al,H as pr,I as it,J as rt,N as ol,O as at,a as Yi,c as qd,j as Yd,k as Xd,m as Zd,n as Qd,o as kt,p as el,q as tl,v as nl,w as il}from"./chunk-J67PFM3O.js";import{$a as lr,Aa as zd,Ca as rr,Da as ar,Ea as zn,Fa as bt,Ga as Wn,Ha as Wd,Ia as or,Ja as Nt,Ka as ae,La as cr,Ma as Gd,Na as Ga,Oa as dr,Pa as nn,Qa as rn,Sa as Bd,Ta as Jd,Wa as Me,Za as Vd,_a as T,a as Ad,aa as z,ba as Ld,ca as nt,d as Re,da as Nd,db as te,e as Wa,f as Cd,ja as Md,k as Xi,ka as qa,l as Hn,la as tr,m as Td,ma as en,n as Zi,o as $d,oa as nr,pa as jd,q as Qi,qa as Fd,r as er,sa as Ud,t as Dd,u as $e,ua as Hd,x as vt,xa as ir,y as Od,z as Pd,za as tn}from"./chunk-SM2KGD4J.js";import{b as Gt}from"./chunk-YW5GHQN2.js";import{a as se,c as Te,e as Ie,f as Ve,j as fe,k as Qc,l as Wi,n as ed}from"./chunk-B266DDBJ.js";import{Ad as Lt,Ba as $c,Bb as Uc,Ca as Ot,Cb as Hc,Cc as ld,Dc as le,Ea as Dc,Fa as A,Fd as md,Ga as Oc,Ha as xe,Id as pd,Ja as Fi,Jd as fd,Ka as Pc,Kb as zc,Kd as re,La as Da,Lb as Pt,Ma as Oa,Na as Pa,Nb as La,O as xc,Ob as Wc,Pa as Lc,Pb as Jt,Qa as Nc,R as Ic,Rb as Be,T as $a,Ta as Mc,Tb as Je,Wb as rd,Y as me,Yb as qi,Z as qe,Zb as ad,_ as Rc,_b as od,a as gc,aa as Y,ac as sd,bb as jc,d as yc,da as Ac,e as wc,ic as F,kb as Fc,mc as K,o as Ta,oa as Cc,oc as Ne,pa as Tc,pc as cd,qa as H,qc as Gi,va as jn,wa as M,wd as $,xa as Ge,xc as dd,xd as ud,ya as ji,yd as Qt,za as Bt,zd as wt}from"./chunk-NLZUI234.js";import{a as _r,b as Bn}from"./chunk-EGN2HFRU.js";import{A as Mn,B as D,C as gt,D as j,E as B,H as Z,a as Li,d as Ni,o as vc,q as bc,s as kc,u as Ec,v as Mi,w as Sc,y,z as g}from"./chunk-KTXU5WU6.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},we=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ke=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function ln(e){try{return await e()}catch(t){throw t instanceof L?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Qa(e){try{return await e()}catch(t){throw t instanceof we?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as cg}from"node:crypto";import dg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var un=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var Pl=1,jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],eo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],lg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],ug=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,gr=30,yr=5e3,Ll=4,mg=50;function ot(e,t){if(!ug.test(e))throw new L(`${t} must be a stable lowercase id`)}function pg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Jn(e){let t=lg.filter(r=>e[r]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function no(e,t){return A(e)===A(t)}function Nl(e,t){if(t.polarity==="equals")return no(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let i=t.value;return e.every(r=>i.includes(r))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function Ml(e){let t=Jn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Nl(i.observed,t)===(i.expected==="pass"))}function fg(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,i=t.value;return!Array.isArray(n)||!Array.isArray(i)||i.some(r=>!n.includes(r))}return!no(e.value,t.value)}function hg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||A(e.scope)!==A(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return fg(Jn(e),Jn(t))||n[t.enforcement]<n[e.enforcement]||i}function _g(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,i=Number(t)+Number(n);if(e.field!==void 0&&i!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new L("items source equals/state requires field")}function gg(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new L("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new L("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new L("dependency_kind source source_kind_state must be present or missing")}function yg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new L("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new L("prose_edge_gap exemption selectors must not be empty")}}function io(e){ot(e.id,"measurement.id"),e.max_cost!==void 0&&pg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${eo.join(", ")}`);let n=Reflect.get(t,"kind");if(!eo.includes(n))throw new L(`measurement.source.kind must be one of ${eo.join(", ")}`);let i=t;if(i.kind==="items"&&_g(i),i.kind==="dependency_kind"&&gg(i),i.kind==="prose_edge_gap"&&yg(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new L(`${i.kind} source requires field`);return i.kind==="provider"&&(ot(i.provider,"provider source provider"),ot(i.key,"provider source key")),e}function ro(e){if(ot(e.id,"assertion.id"),ot(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=Jn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new L("retired assertion requires retire_reason");e.scope.kind==="filter"&&ot(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new L("assertion negative control requires pass and fail cases");if(!Ml(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function wg(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)ot(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!jt.includes(t))throw new L(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new L(`gate provider policy trigger ${t} is invalid`)}}function jl(e){if(ot(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)ot(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${jt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!jt.includes(t))throw new L(`gate trigger must be one of ${jt.join(", ")}`);return e.provider_policy&&wg(e.provider_policy),e}function mn(e){if(e.version!==Pl)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(io(i),t.has(`measurement:${i.id}`))throw new L(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(ro(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){jl(i);let r=i.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(r.length>0)throw new L(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new L(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of Fl(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function ao(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ao(n,t)}function Fl(e){let t=new Map,n=(i,r)=>{let a=t.get(i)??[];a.push(r),t.set(i,a)};for(let i of e.assertions)n(i.measurement_id,`assertion ${i.id}`),i.scope.kind==="filter"&&n(i.scope.measurement_id,`assertion ${i.id} scope`);for(let i of e.measurements){if(i.source.kind!=="derived")continue;let r=[];ao(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function vg(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let a=n.pop();if(i.has(a))continue;i.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&ao(o.source.expression,n)}return r}function Vn(){return{version:Pl,measurements:[],assertions:[],gates:[]}}function bg(e,t){let n=t.items.filter(i=>(e.statuses===void 0||e.statuses.includes(i.status))&&(e.types===void 0||e.types.includes(i.type))&&(e.tags===void 0||e.tags.every(r=>i.tags?.includes(r)))&&(e.field===void 0||(()=>{let r=i[e.field];if(e.state!==void 0){let a=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?a:!a}return no(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function kg(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function Eg(e,t){let n=[],i=$a(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=$a(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&kg(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Sg(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let i=e[n];if(Array.isArray(i)){for(let r of i)if(typeof r=="string")t.push(r);else if(typeof r=="object"&&r!==null){let a=Reflect.get(r,"text");typeof a=="string"&&t.push(a)}}}return t}function xg(e,t,n,i){return e.some(r=>r.holder_id.trim().toLowerCase()===t.toLowerCase()&&(r.target_id===void 0||r.target_id.trim().toLowerCase()===n.toLowerCase())&&(r.text_contains===void 0||i.toLowerCase().includes(r.text_contains.trim().toLowerCase())))}function to(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Ig(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(to(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(to(o.id,s));for(let s of Sg(o)){let c=[...s.matchAll(r)].map(d=>d[0]);a+=c.length,i.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:a}}function Rg(e,t){let n=Ig(t.items),i=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=to(o.holder_id,d);if(n.linked_pairs.has(l)||xg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],a=r.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function Ag(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function Cg(e,t){let n=t.items.filter(i=>{let r=i[e.link],a=Array.isArray(r)&&r.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Tg(e,t){let n=e.source;return n.kind==="items"?bg(n,t):n.kind==="dependency_kind"?Eg(n,t):n.kind==="prose_edge_gap"?Rg(n,t):n.kind==="history"?Ag(n,t):n.kind==="links"?Cg(n,t):null}function Ul(e,t){return e.reduce((n,i)=>({units:n.units+i.units,items_scanned:n.items_scanned+i.items_scanned,history_entries:n.history_entries+i.history_entries,provider_calls:n.provider_calls+i.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function $g(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,i)=>n+i,0);if(e==="subtract")return t.slice(1).reduce((n,i)=>n-i,t[0]);if(e==="multiply")return t.reduce((n,i)=>n*i,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,i)=>n/i,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Hl(e,t,n){let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o],o)}});return await Promise.all(a),i}async function zl(e,t,n,i,r){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await Wl(o,t,n,i,r);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[s.cost];return r.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await Hl(e.operands,Ll,o=>zl(o,t,n,i,r));return{value:$g(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Dg(e,t,n,i,r){io(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await zl(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Tg(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-a},l=Ul([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new we(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${cg("sha256").update(A(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Wl(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let a=r.cache.get(e.id);if(a)return a;let o=Dg(e,t,n,i,r).catch(s=>{if(s instanceof Ke&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Ke(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function oo(e,t,n=[e]){return Wl(e,t,n,[],{cache:new Map,charged:new Set})}function Og(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function Pg(e,t,n={}){ro(e);let i=Jn(e),r=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:i,distance:Og(t.value,i),verdict:r?"retired":Nl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Ml(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Lg(e,t,n,i){let r=vg(e,t);if(r.size===0)return;let a=e.provider_policy,o=a?.triggers[i];if(!a||!o)throw new we(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!s.has(d))throw new we(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new we(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new we(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new we(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Ol(e,t,n,i,r){try{return await oo(n,i,r)}catch(a){if(a instanceof Ke){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new we(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function ql(e,t,n,i){mn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new we(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new we(`assurance gate ${e} does not declare trigger ${i.trigger}`);Lg(r,t,n,i.trigger);let a=await Hl(r.assertion_ids,Ll,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await Ol(r.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Pg(d,await Ol(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:r.id,tree_id:n.tree_id,trigger:i.trigger,dry_run:i.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Ul(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function wr(e){return dg.join(e,"assurance.json")}async function Gl(e){let t=await B(wr(e));return t===null?Vn():vr(t)}function vr(e){try{return mn(JSON.parse(e))}catch(t){throw new g("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function br(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Ng(e,t){e==="measurement"?io(t):e==="assertion"?ro(t):jl(t)}async function Kn(e,t){let n=structuredClone(br(await Gl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Bl(e,t,n){let i=br(await Gl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function kr(e,t,n,i={}){Ng(t,n);let r=await T(e),a=z(i.author,r.author_default),o=await nn({pmRoot:e,filePath:wr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Vn():vr(s),d=br(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&hg(d[l],n)){let m=n.authorization_decision;if(!m||!i.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),mn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
1
|
+
import{c as Et,d as sn,e as cn,f as dn,g as Tl,j as Dl}from"./chunk-R3EA3SDW.js";import{a as Cl}from"./chunk-ON5WFDCG.js";import{d as Q,h as Ya,s as El}from"./chunk-L5GX2FGZ.js";import{a as Na,c as Ui,d as Hi,e as Vc,g as Kc,h as ja,i as Yc,j as Kt,k as Yt,l as Xc,m as Zc,n as Fa,o as td,p as Xt,q as Zt,r as nd,s as id,t as Ua}from"./chunk-B4ZQJEMT.js";import{a as za}from"./chunk-SVOOGGAK.js";import{B as hd,C as Bi,D as _d,E as Ha,G as gd,H as yd,J as wd,K as vd,L as Ji,U as Vi}from"./chunk-Z26ZPQH6.js";import{K as $l}from"./chunk-I4X6AKOO.js";import{A as Al,I as Za,w as Il,y as Xa,z as Rl}from"./chunk-F6UQJJYB.js";import{$ as ur,Aa as Ka,C as Sd,G as xd,H as Id,I as Rd,L as sr,Na as wl,Oa as vl,Sa as bl,Ta as kl,aa as Kd,ba as Ba,ca as qn,ea as Ja,i as Ki,ia as sl,ja as cl,ka as dl,la as ll,m as Fn,ma as fr,n as bd,o as kd,oa as ul,p as Un,pa as ml,qa as pl,ra as Mt,sa as fl,ta as an,ua as hl,va as Va,wa as on,x as Ed,xa as _l,ya as gl,za as yl}from"./chunk-OASYSUOH.js";import{a as qc,b as Vt,c as Ma,d as Gc,e as Bc,f as tt,g as zi,h as Jc,i as yt}from"./chunk-4GN2ZPT5.js";import{m as Gn,o as hr,v as Sl,y as xl}from"./chunk-6VDRAJYX.js";import{B as mr,D as rl,E as ge,F as ye,G as al,H as pr,I as it,J as rt,N as ol,O as at,a as Yi,c as qd,j as Yd,k as Xd,m as Zd,n as Qd,o as kt,p as el,q as tl,v as nl,w as il}from"./chunk-BZSACRVX.js";import{$a as lr,Aa as zd,Ca as rr,Da as ar,Ea as zn,Fa as bt,Ga as Wn,Ha as Wd,Ia as or,Ja as Nt,Ka as ae,La as cr,Ma as Gd,Na as Ga,Oa as dr,Pa as nn,Qa as rn,Sa as Bd,Ta as Jd,Wa as Me,Za as Vd,_a as T,a as Ad,aa as z,ba as Ld,ca as nt,d as Re,da as Nd,db as te,e as Wa,f as Cd,ja as Md,k as Xi,ka as qa,l as Hn,la as tr,m as Td,ma as en,n as Zi,o as $d,oa as nr,pa as jd,q as Qi,qa as Fd,r as er,sa as Ud,t as Dd,u as $e,ua as Hd,x as vt,xa as ir,y as Od,z as Pd,za as tn}from"./chunk-IQKLJFJE.js";import{b as Gt}from"./chunk-ML5JIUM6.js";import{a as se,c as Te,e as Ie,f as Ve,j as fe,k as Qc,l as Wi,n as ed}from"./chunk-TUN4M757.js";import{Ad as Qt,Ba as $c,Bb as Uc,Bd as wt,Ca as Ot,Cb as Hc,Cc as ld,Cd as Lt,Dc as le,Ea as Dc,Fa as A,Ga as Oc,Ha as xe,Hd as md,Ja as Fi,Ka as Pc,Kb as zc,Kd as pd,La as Da,Lb as Pt,Ld as fd,Ma as Oa,Md as re,Na as Pa,Nb as La,O as xc,Ob as Wc,Pa as Lc,Pb as Jt,Qa as Nc,R as Ic,Rb as Be,T as $a,Ta as Mc,Tb as Je,Wb as rd,Y as me,Yb as qi,Z as qe,Zb as ad,_ as Rc,_b as od,a as gc,aa as Y,ac as sd,bb as jc,d as yc,da as Ac,e as wc,ic as F,kb as Fc,mc as K,o as Ta,oa as Cc,oc as Ne,pa as Tc,pc as cd,qa as H,qc as Gi,va as jn,wa as M,xa as Ge,xc as dd,ya as ji,yd as $,za as Bt,zd as ud}from"./chunk-6L4KKRK7.js";import{a as _r,b as Bn}from"./chunk-EGN2HFRU.js";import{A as Mn,B as D,C as gt,D as j,E as B,H as Z,a as Li,d as Ni,o as vc,q as bc,s as kc,u as Ec,v as Mi,w as Sc,y,z as g}from"./chunk-7SZPZOIC.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},we=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ke=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function ln(e){try{return await e()}catch(t){throw t instanceof L?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Qa(e){try{return await e()}catch(t){throw t instanceof we?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as cg}from"node:crypto";import dg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var un=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var Pl=1,jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],eo=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],lg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],ug=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,gr=30,yr=5e3,Ll=4,mg=50;function ot(e,t){if(!ug.test(e))throw new L(`${t} must be a stable lowercase id`)}function pg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Jn(e){let t=lg.filter(r=>e[r]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function no(e,t){return A(e)===A(t)}function Nl(e,t){if(t.polarity==="equals")return no(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let i=t.value;return e.every(r=>i.includes(r))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function Ml(e){let t=Jn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Nl(i.observed,t)===(i.expected==="pass"))}function fg(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,i=t.value;return!Array.isArray(n)||!Array.isArray(i)||i.some(r=>!n.includes(r))}return!no(e.value,t.value)}function hg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||A(e.scope)!==A(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return fg(Jn(e),Jn(t))||n[t.enforcement]<n[e.enforcement]||i}function _g(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,i=Number(t)+Number(n);if(e.field!==void 0&&i!==1)throw new L("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new L("items source equals/state requires field")}function gg(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new L("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new L("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new L("dependency_kind source source_kind_state must be present or missing")}function yg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new L("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new L("prose_edge_gap exemption selectors must not be empty")}}function io(e){ot(e.id,"measurement.id"),e.max_cost!==void 0&&pg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${eo.join(", ")}`);let n=Reflect.get(t,"kind");if(!eo.includes(n))throw new L(`measurement.source.kind must be one of ${eo.join(", ")}`);let i=t;if(i.kind==="items"&&_g(i),i.kind==="dependency_kind"&&gg(i),i.kind==="prose_edge_gap"&&yg(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new L(`${i.kind} source requires field`);return i.kind==="provider"&&(ot(i.provider,"provider source provider"),ot(i.key,"provider source key")),e}function ro(e){if(ot(e.id,"assertion.id"),ot(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=Jn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new L("retired assertion requires retire_reason");e.scope.kind==="filter"&&ot(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new L("assertion negative control requires pass and fail cases");if(!Ml(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function wg(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)ot(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!jt.includes(t))throw new L(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new L(`gate provider policy trigger ${t} is invalid`)}}function jl(e){if(ot(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)ot(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${jt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!jt.includes(t))throw new L(`gate trigger must be one of ${jt.join(", ")}`);return e.provider_policy&&wg(e.provider_policy),e}function mn(e){if(e.version!==Pl)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(io(i),t.has(`measurement:${i.id}`))throw new L(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(ro(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){jl(i);let r=i.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(r.length>0)throw new L(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new L(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of Fl(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function ao(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ao(n,t)}function Fl(e){let t=new Map,n=(i,r)=>{let a=t.get(i)??[];a.push(r),t.set(i,a)};for(let i of e.assertions)n(i.measurement_id,`assertion ${i.id}`),i.scope.kind==="filter"&&n(i.scope.measurement_id,`assertion ${i.id} scope`);for(let i of e.measurements){if(i.source.kind!=="derived")continue;let r=[];ao(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function vg(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let a=n.pop();if(i.has(a))continue;i.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&ao(o.source.expression,n)}return r}function Vn(){return{version:Pl,measurements:[],assertions:[],gates:[]}}function bg(e,t){let n=t.items.filter(i=>(e.statuses===void 0||e.statuses.includes(i.status))&&(e.types===void 0||e.types.includes(i.type))&&(e.tags===void 0||e.tags.every(r=>i.tags?.includes(r)))&&(e.field===void 0||(()=>{let r=i[e.field];if(e.state!==void 0){let a=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?a:!a}return no(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function kg(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function Eg(e,t){let n=[],i=$a(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=$a(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&kg(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Sg(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let i=e[n];if(Array.isArray(i)){for(let r of i)if(typeof r=="string")t.push(r);else if(typeof r=="object"&&r!==null){let a=Reflect.get(r,"text");typeof a=="string"&&t.push(a)}}}return t}function xg(e,t,n,i){return e.some(r=>r.holder_id.trim().toLowerCase()===t.toLowerCase()&&(r.target_id===void 0||r.target_id.trim().toLowerCase()===n.toLowerCase())&&(r.text_contains===void 0||i.toLowerCase().includes(r.text_contains.trim().toLowerCase())))}function to(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Ig(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(to(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(to(o.id,s));for(let s of Sg(o)){let c=[...s.matchAll(r)].map(d=>d[0]);a+=c.length,i.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:a}}function Rg(e,t){let n=Ig(t.items),i=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=to(o.holder_id,d);if(n.linked_pairs.has(l)||xg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],a=r.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function Ag(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function Cg(e,t){let n=t.items.filter(i=>{let r=i[e.link],a=Array.isArray(r)&&r.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Tg(e,t){let n=e.source;return n.kind==="items"?bg(n,t):n.kind==="dependency_kind"?Eg(n,t):n.kind==="prose_edge_gap"?Rg(n,t):n.kind==="history"?Ag(n,t):n.kind==="links"?Cg(n,t):null}function Ul(e,t){return e.reduce((n,i)=>({units:n.units+i.units,items_scanned:n.items_scanned+i.items_scanned,history_entries:n.history_entries+i.history_entries,provider_calls:n.provider_calls+i.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function $g(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,i)=>n+i,0);if(e==="subtract")return t.slice(1).reduce((n,i)=>n-i,t[0]);if(e==="multiply")return t.reduce((n,i)=>n*i,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,i)=>n/i,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Hl(e,t,n){let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o],o)}});return await Promise.all(a),i}async function zl(e,t,n,i,r){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await Wl(o,t,n,i,r);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[s.cost];return r.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await Hl(e.operands,Ll,o=>zl(o,t,n,i,r));return{value:$g(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Dg(e,t,n,i,r){io(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await zl(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Tg(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-a},l=Ul([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new we(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${cg("sha256").update(A(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Wl(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let a=r.cache.get(e.id);if(a)return a;let o=Dg(e,t,n,i,r).catch(s=>{if(s instanceof Ke&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Ke(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function oo(e,t,n=[e]){return Wl(e,t,n,[],{cache:new Map,charged:new Set})}function Og(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function Pg(e,t,n={}){ro(e);let i=Jn(e),r=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:i,distance:Og(t.value,i),verdict:r?"retired":Nl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Ml(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Lg(e,t,n,i){let r=vg(e,t);if(r.size===0)return;let a=e.provider_policy,o=a?.triggers[i];if(!a||!o)throw new we(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!s.has(d))throw new we(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new we(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new we(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new we(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Ol(e,t,n,i,r){try{return await oo(n,i,r)}catch(a){if(a instanceof Ke){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new we(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function ql(e,t,n,i){mn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new we(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new we(`assurance gate ${e} does not declare trigger ${i.trigger}`);Lg(r,t,n,i.trigger);let a=await Hl(r.assertion_ids,Ll,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await Ol(r.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Pg(d,await Ol(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:r.id,tree_id:n.tree_id,trigger:i.trigger,dry_run:i.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Ul(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function wr(e){return dg.join(e,"assurance.json")}async function Gl(e){let t=await B(wr(e));return t===null?Vn():vr(t)}function vr(e){try{return mn(JSON.parse(e))}catch(t){throw new g("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function br(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Ng(e,t){e==="measurement"?io(t):e==="assertion"?ro(t):jl(t)}async function Kn(e,t){let n=structuredClone(br(await Gl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Bl(e,t,n){let i=br(await Gl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function kr(e,t,n,i={}){Ng(t,n);let r=await T(e),a=z(i.author,r.author_default),o=await nn({pmRoot:e,filePath:wr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Vn():vr(s),d=br(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&hg(d[l],n)){let m=n.authorization_decision;if(!m||!i.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),mn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
2
|
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function so(e,t,n={}){let i=Vn();i.measurements=structuredClone(t.measurements),i.assertions=structuredClone(t.assertions),i.gates=structuredClone(t.gates),mn(i);let r=await T(e),a=z(n.author,r.author_default),o=await nn({pmRoot:e,filePath:wr(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Vn():vr(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let _=m.find(w=>w.id===h.id);if(!_){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(A(_)!==A(h))throw new L(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,i.measurements,"measurement"),u(c.assertions,i.assertions,"assertion"),u(c.gates,i.gates,"gate"),mn(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 Jl(e,t,n,i={}){let r=await T(e),a=z(i.author,r.author_default),o=await nn({pmRoot:e,filePath:wr(e),op:`assurance:${t}:remove`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Vn():vr(s);if(t==="measurement"){let u=Fl(c).get(n);if(u&&u.length>0)throw new L(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new L(`assurance assertion ${n} is referenced by gate`);let d=br(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new L(`assurance ${t} ${n} not found`);return d.splice(l,1),mn(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 Vl(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await T(e);await dr({pmRoot:e,op:"assurance:gate:verdict",author:z(n.author,i.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:gr,lockWaitMs:yr})}async function Kl(e,t={}){let n=t.limit??mg;if(!Number.isInteger(n)||n<1||n>un)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${un}`);return(await nt(cr(e),ae)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var Yn={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Er={type:"array",minItems:1,maxItems:Da,items:Yn},Yl={...Er,items:{...Yn,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Mg={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,Er])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:Yn,id:Yn}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Yl}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Er}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Yl,authors:Er}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Da,items:{type:"array",minItems:2,maxItems:2,items:Yn}}}}]}}},LC={$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:Pc,items:Mg}}};(function(){try{var e=typeof window<"u"?window:typeof 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 Xl(e,t,n,i){let r=await kt(e).catch(()=>null);return r===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Zl(r,t,n,i)}function jg(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Zl(e,t,n=5,i=!1){let r=[],a=new Map,o=e.policies.filter(_=>_.rule.kind==="require_fields"),s=o.filter(_=>_.subject?.operations===void 0),c=new Set,d=0,l=0,u=0,m=0,f=0,p=Mc(e);for(let _ of t){let w=p({operation:"",author:"",before:_,after:_,completeness_only:!0});d+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(k=>c.add(k.policy_id));let v=w.decisions.filter(k=>!k.satisfied);if(v.length===0)continue;m+=1;let E=a.get(_.type)??{items:0,violations:0,missing_fields:0};E.items+=1;for(let k of v)u+=1,E.violations+=1,E.missing_fields+=k.missing_fields.length,k.effect==="refuse"&&(f+=1),r.length<n&&r.push({id:_.id,type:_.type,status:_.status,decision:k});a.set(_.type,E)}let h=i||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:jg(o.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(a),violations:r,violations_truncated:r.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...i?["validate_completeness_source_incomplete"]:[]]}}import Fg 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 Ug(){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 tu(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new g("Policy definition must be valid JSON.",y.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("Policy definition must be an object.",y.USAGE);return t}async function Hg(e,t){let n=M(process.cwd(),e.path);await te(n);let i=await T(n);return{pmRoot:n,settings:i,author:z(t,i.author_default)}}function Ql(e,t,n,i){if(e==="policy-mode")return Pa({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let a=Oa(i.definition),o=Pa({...n,policies:[...r,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
@@ -49,7 +49,7 @@ ${d}`,y.GENERIC_FAILURE)}}function Hm(e){let t=e.trim(),n=t.includes("@file:")?t
|
|
|
49
49
|
`,conflict_paths:c,paths_from_theirs:d,preferred:r}}import Zr from"node:path";import{execFile as hS}from"node:child_process";import{createHash as Sf}from"node:crypto";import{readdir as _S}from"node:fs/promises";import gS from"node:path";import{promisify as yS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var ut=yS(hS),Xr=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function rM(e,t,n){let i=t.trim(),r=/^(['"])(.*)\1$/su.exec(i)?.[2]??i;for(let a of["rebase-merge","rebase-apply"])try{let{stdout:o}=await ut("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Bn(o.trim(),128))?.trim();if(s===void 0||!Xr.test(s))continue;let{stdout:c}=await ut("git",["rev-parse","--verify",`${s}:${r}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:s,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(a=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(a)))try{let{stdout:a}=await ut("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!Xr.test(o))return;let{stdout:c}=await ut("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Sf(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:o,original_blob:d}}catch{}}function xf(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&Xr.test(t.original_head)&&typeof t.original_blob=="string"&&Xr.test(t.original_blob)}async function If(e,t,n,i){if(i!==void 0&&Sf(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(i)}\0`).update(i).digest("hex")!==n.original_blob)return!1;try{let{stdout:r}=await ut("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),a=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await _S(r.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await ut("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await ut("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await ut("git",["hash-object","--",gS.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await ut("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var wS=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,vS=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,ea=2048,bS=64,kS=1e5,ES=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function mt(e){return wS.test(e)}var SS=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ta="bounded_non_sensitive_scalars_v1",xS=new Set(["open","in_progress","blocked","closed","canceled"]),IS=new Set(["risk","confidence","severity"]),RS=new Set(["low","medium","high","critical"]),Af=new Map([["priority",new Set([0,1,2,3,4].map(A))],["status",new Set([...xS].map(A))],...[...IS].map(e=>[e,new Set([...RS].map(A))])]);function Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cf(e,t){return Object.keys(e).every(n=>t.has(n))}function Qr(e){return Array.isArray(e)&&e.length<=ea&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function vi(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let i=t.pop();if(n+=1,n>kS||i.depth>bS)return!1;if(Array.isArray(i.value))for(let r of i.value)t.push({value:r,depth:i.depth+1});else if(Qe(i.value))for(let r of Object.values(i.value))t.push({value:r,depth:i.depth+1})}return!0}function Tf(e){if(!Qe(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[Cf(e,SS),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),vi(e.base),vi(e.ours),vi(e.theirs),vi(e.retained),vi(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function AS(e){if(!Qe(e))return!1;let t=Object.entries(e);return t.length<=ea&&t.every(([n,i])=>n.length>0&&n.length<=256&&typeof i=="string"&&/^[a-f0-9]{64}$/u.test(i))}function CS(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||Zr.posix.isAbsolute(e))return!1;let n=Zr.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&Zr.posix.basename(n,Zr.posix.extname(n))===t}function TS(e){return!Qr(e.fields_from_theirs)||!Qr(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>ea||!e.decisions.every(Tf)?!1:e.merged_field_hashes===void 0||AS(e.merged_field_hashes)}function $S(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],i=[void 0,"clone_local","hash_only","bounded_inline","mixed"],r=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&i.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ta)&&r.includes(e.evidence_source)}function DS(e){return typeof e.created_at=="string"&&Qt(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Qt(e.reconciled_at))}function Rf(e,t){if(!Qe(t)||ra(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(r=>r==="pm_value_hash"||r==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let i=t.pm_value;return(i===null||Af.get(e)?.has(A(i))===!0)&&At(i)===t.pm_value_hash}function OS(e){if(!e.decisions.every(i=>i.base===null&&i.ours===null&&i.theirs===null&&Rf(i.field,i.retained)&&Rf(i.field,i.discarded)))return!1;let t=e.decisions.reduce((i,r)=>i+(Qe(r.retained)&&Object.hasOwn(r.retained,"pm_value")?1:0)+(Qe(r.discarded)&&Object.hasOwn(r.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===ta)}function PS(e){return e.operation!==void 0&&!xf(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function LS(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!Cf(e,ES)?"required_fields":typeof e.id!="string"||!mt(e.id)?"receipt_id":typeof e.item_id!="string"||!vS.test(e.item_id)?"item_id":CS(e.item_path,e.item_id)?null:"item_path"}function na(e,t){if(!Qe(e))return"required_fields";let n=LS(e);return n!==null?n:PS(e)?TS(e)?$S(e)?DS(e)?t==="durable"&&!OS(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function ia(e){if(!Qe(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(i=>!Qe(i)||!Object.hasOwn(i,"retained")||!Object.hasOwn(i,"discarded")?i:{base:V(void 0),ours:V(void 0),theirs:V(void 0),...i})}}function $f(e){if(!Qe(e))return;if(!Qr(e.fields_from_theirs))return"fields_from_theirs";if(!Qr(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>ea)return"decisions";let t=e.decisions.findIndex(n=>!Tf(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function ps(e,t){return na(e,t)===null}function ra(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function fs(e,t){let n=xn(t),i=At(n?void 0:t);return!n&&(t===null||Af.get(e)?.has(A(t))===!0)?{pm_value_hash:i,pm_value:t}:{pm_value_hash:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7bab0a8e-842c-5588-a0b2-22ef261ddb06")}catch{}})();var HS=US(NS),aa=100;async function hs(e){try{let{stdout:t}=await HS("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Pf(e,t){let n=ie.dirname(ie.resolve(e,t));for(let i=0;i<12;i+=1){if(await D(ie.join(n,"settings.json")))return n;let r=ie.dirname(n);if(r===n)break;n=r}return null}function In(e){return ie.join(e,"merge-receipts")}function Tt(e){return`${e}.json`}async function Df(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Bn(e.receiptPath,_r)}catch(a){if(gt(a))return null;throw a}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=ia(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!ps(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ie.basename(e.receiptPath)!==Tt(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:i,...r}=n;return{path:e.receiptPath,fingerprints:ki(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...r,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
50
50
|
`}}function bi(e,t=!1){return xe(A({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:xe(A(V(n.retained))),discarded_hash:xe(A(V(n.discarded)))})):oa(e).decisions}))}function ki(e){let t=[bi(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(bi(e,!0)),t}function zS(e,t){let{reconciled_at:n,settlement:i,...r}=e;return t.state==="reconciled"?{...r,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...r,state:"pending"}}async function WS(e,t,n){let i=new Map;for(let r of t){let a=e.get(r.id);if(r.state!=="reconciled"||a===void 0)continue;let o=i.get(a.item_id);if(o===void 0){try{o=await nt(ie.join(n,"history",`${a.item_id}.jsonl`),a.item_id),bt(o).ok||(o=[])}catch{o=[]}i.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=A({...oa(a),...s?{reason:a.settlement,operation:a.operation}:{}});if(!o.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[s?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(m=>A(m)===c)})){let{reconciled_at:d,settlement:l,...u}=a;e.set(a.id,{...u,state:"pending"})}}}function oa(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:ra(t.retained)??At(xn(t.retained)?void 0:t.retained),discarded_hash:ra(t.discarded)??At(xn(t.discarded)?void 0:t.discarded)}))}}async function AM(e){let t=await hs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,r=ie.basename(i,ie.extname(i)),a={version:1,id:MS(),item_path:i.replaceAll("\\","/"),item_id:r,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(s=>({...s,base:V(s.base),ours:V(s.ours),theirs:V(s.theirs),retained:V(s.retained),discarded:V(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:$(),value_availability:"clone_local"};await Mn(t),await Z(ie.join(t,Tt(a.id)),`${JSON.stringify(a,null,2)}
|
|
51
51
|
`);let o=await Pf(e.cwd,a.item_path);if(o!==null){let s=In(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:fs(u.field,u.retained),discarded:fs(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:ta};await Mn(s),await Z(ie.join(s,Tt(a.id)),`${JSON.stringify(l,null,2)}
|
|
52
|
-
`)}return a}async function Of(e,t){let n;try{n=await jS(e)}catch(s){let c=await qS(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let i=[],r=0,a=[],o=(s,c)=>{if(r+=1,a.length>=aa)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...mt(d)?{receipt_id:d}:{candidate_name_hash:xe(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await GS(e,s,t);c.receipt!==void 0?i.push(c.receipt):o(s,c)}return{receipts:i,invalid_evidence_count:r,invalid_evidence:a,invalid_evidence_truncated:r>a.length}}async function qS(e,t,n=FS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ie.dirname(i);if(a===i)return!0;i=a}}async function GS(e,t,n){let i;try{i=await Bn(ie.join(e,t),_r)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=ia(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=na(r,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:$f(r)}:{}};let o=r;if(t!==Tt(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function BS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-GAFC52LQ.js"),r=await JS(t),a=await i(r?.workspace??e,In(t),n.map(o=>Tt(o.id)),_r,r?.directory);return n.flatMap(o=>{try{let s=ia(JSON.parse(a.get(Tt(o.id))??""));if(na(s,"durable")!==null)return[];let c=s,d=ki(o);return c.id===o.id&&ki(c).some(l=>d.includes(l))?[o.id]:[]}catch{return[]}})}async function JS(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,i=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!i))try{if(await Ct(e)!==await Ct(i))return;let r=ie.relative(await Ct(t),await Ct(n)),a=r===".."||r.startsWith(`..${ie.sep}`)||ie.isAbsolute(r),o=In(a?ie.join(await Ct(t),".agents","pm"):await Ct(n)),[s,c]=await Promise.all([Ct(o),Ct(In(n))]);return s!==c?void 0:{workspace:t,directory:o}}catch{return}}async function pt(e,t={}){let n=await hs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Of(n,"clone_local"),r=t.pmRoot??ie.join(e,".agents","pm"),a=await Of(In(r),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of i.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?ki(u):[bi(u)]).includes(bi(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<aa&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}o.set(u.id,m===void 0?u:zS(u,m))}await WS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await BS(e,r,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...o.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:i.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...i.invalid_evidence,...a.invalid_evidence,...c].slice(0,aa),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>aa,clone_local_evidence_resolved:n!==null}}function Lf(e,t,n){let i=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),r=[...e].filter(a=>!i.has(a));if(r.length!==0)throw new g(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,y.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Rn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function CM(e,t,n={}){let i=await hs(e);if(i===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let r=t.evidence_source??"clone_local";if(!ps(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=ie.join(i,Tt(t.id)),s=await Pf(e,t.item_path),c=s===null?null:ie.join(In(s),Tt(t.id)),d=(await Promise.all([Df({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Df({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[bi(t)]:ki(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function TM(e){let t=await pt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as VS}from"node:crypto";import sa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var KS="2026-08-09T16:15:18.000Z",Mf=Symbol("pre-durable-disposition-eligible");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _s(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let i=e[n];if(!(n in e)||typeof i!="string"||i.length===0||i.length>256||i.includes("\0")||t.has(i))return!1;t.add(i)}return!0}function Nf(e){return ft(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function jf(e,t){if(typeof e!="string")return!1;let n=sa.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!sa.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(sa.posix.basename(n)===`${t}.toon`||sa.posix.basename(n)===`${t}.md`)}function YS(e,t){return typeof e.receipt_id=="string"&&mt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&jf(e.item_path,t)}function Ff(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,a=Array.isArray(r)?new Set(r.flatMap(o=>Nf(o)?[o.field]:[])):new Set;return _s(t)&&_s(n)&&_s(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Nf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function XS(e,t){return YS(e,t)&&Ff(e)}function ZS(e,t){return typeof e.receipt_id=="string"&&mt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&jf(e.item_path,t)&&Ff(e)}function QS(e){return e[Mf]===!0}function Uf(e,t){if(!ft(e)||!ft(e.context))return[];let n=e.context.merge;return!ft(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!ft(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:XS(i,t),[Mf]:ZS(i,t),...typeof e.ts=="string"&&Qt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Hf(e,t,n){if(!ft(e)||e.op!=="merge_reconcile")return[];if(!ft(e.context)||!ft(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!ft(r)||typeof r.receipt_id!="string"||!mt(r.receipt_id)||typeof r.original_history_line!="number"||!Number.isSafeInteger(r.original_history_line)||r.original_history_line<1||typeof r.original_event_ts!="string"||!Qt(r.original_event_ts)||r.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:r.receipt_id,originalHistoryLine:r.original_history_line,originalEventTimestamp:r.original_event_ts,auditHistoryLine:n,reason:r.reason}])}function zf(e,t,n=[]){let i=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;i.set(o,Math.max(i.get(o)??0,a.auditHistoryLine))}let r=a=>QS(a)&&a.eventTimestamp!==void 0&&Lt(a.eventTimestamp,KS)<0&&(i.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!r(a)).map(a=>({item_id:a.itemId,history_line:a.line,...mt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:VS("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as e0}from"node:buffer";import{readFile as t0}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function n0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new g("History salvage cannot discard a potentially complete record with trailing corruption.",y.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("History salvage would conceal interior corruption or a malformed record.",y.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new g("History salvage requires complete history records before the invalid tail.",y.CONFLICT,{code:"history_salvage_refused"});return n}function i0(e){if($e(e))throw new g("Resolve history merge conflicts before salvage.",y.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,i,r=0;for(let[o,s]of e.split(`
|
|
52
|
+
`)}return a}async function Of(e,t){let n;try{n=await jS(e)}catch(s){let c=await qS(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let i=[],r=0,a=[],o=(s,c)=>{if(r+=1,a.length>=aa)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...mt(d)?{receipt_id:d}:{candidate_name_hash:xe(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await GS(e,s,t);c.receipt!==void 0?i.push(c.receipt):o(s,c)}return{receipts:i,invalid_evidence_count:r,invalid_evidence:a,invalid_evidence_truncated:r>a.length}}async function qS(e,t,n=FS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ie.dirname(i);if(a===i)return!0;i=a}}async function GS(e,t,n){let i;try{i=await Bn(ie.join(e,t),_r)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=ia(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=na(r,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:$f(r)}:{}};let o=r;if(t!==Tt(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function BS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-5H6RMRTK.js"),r=await JS(t),a=await i(r?.workspace??e,In(t),n.map(o=>Tt(o.id)),_r,r?.directory);return n.flatMap(o=>{try{let s=ia(JSON.parse(a.get(Tt(o.id))??""));if(na(s,"durable")!==null)return[];let c=s,d=ki(o);return c.id===o.id&&ki(c).some(l=>d.includes(l))?[o.id]:[]}catch{return[]}})}async function JS(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,i=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!i))try{if(await Ct(e)!==await Ct(i))return;let r=ie.relative(await Ct(t),await Ct(n)),a=r===".."||r.startsWith(`..${ie.sep}`)||ie.isAbsolute(r),o=In(a?ie.join(await Ct(t),".agents","pm"):await Ct(n)),[s,c]=await Promise.all([Ct(o),Ct(In(n))]);return s!==c?void 0:{workspace:t,directory:o}}catch{return}}async function pt(e,t={}){let n=await hs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await Of(n,"clone_local"),r=t.pmRoot??ie.join(e,".agents","pm"),a=await Of(In(r),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of i.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?ki(u):[bi(u)]).includes(bi(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<aa&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}o.set(u.id,m===void 0?u:zS(u,m))}await WS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await BS(e,r,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...o.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:i.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...i.invalid_evidence,...a.invalid_evidence,...c].slice(0,aa),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>aa,clone_local_evidence_resolved:n!==null}}function Lf(e,t,n){let i=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),r=[...e].filter(a=>!i.has(a));if(r.length!==0)throw new g(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,y.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Rn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function CM(e,t,n={}){let i=await hs(e);if(i===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let r=t.evidence_source??"clone_local";if(!ps(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=ie.join(i,Tt(t.id)),s=await Pf(e,t.item_path),c=s===null?null:ie.join(In(s),Tt(t.id)),d=(await Promise.all([Df({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Df({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[bi(t)]:ki(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function TM(e){let t=await pt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as VS}from"node:crypto";import sa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var KS="2026-08-09T16:15:18.000Z",Mf=Symbol("pre-durable-disposition-eligible");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _s(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let i=e[n];if(!(n in e)||typeof i!="string"||i.length===0||i.length>256||i.includes("\0")||t.has(i))return!1;t.add(i)}return!0}function Nf(e){return ft(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function jf(e,t){if(typeof e!="string")return!1;let n=sa.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!sa.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(sa.posix.basename(n)===`${t}.toon`||sa.posix.basename(n)===`${t}.md`)}function YS(e,t){return typeof e.receipt_id=="string"&&mt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&jf(e.item_path,t)}function Ff(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,a=Array.isArray(r)?new Set(r.flatMap(o=>Nf(o)?[o.field]:[])):new Set;return _s(t)&&_s(n)&&_s(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Nf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function XS(e,t){return YS(e,t)&&Ff(e)}function ZS(e,t){return typeof e.receipt_id=="string"&&mt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&jf(e.item_path,t)&&Ff(e)}function QS(e){return e[Mf]===!0}function Uf(e,t){if(!ft(e)||!ft(e.context))return[];let n=e.context.merge;return!ft(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!ft(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:XS(i,t),[Mf]:ZS(i,t),...typeof e.ts=="string"&&Qt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Hf(e,t,n){if(!ft(e)||e.op!=="merge_reconcile")return[];if(!ft(e.context)||!ft(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!ft(r)||typeof r.receipt_id!="string"||!mt(r.receipt_id)||typeof r.original_history_line!="number"||!Number.isSafeInteger(r.original_history_line)||r.original_history_line<1||typeof r.original_event_ts!="string"||!Qt(r.original_event_ts)||r.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:r.receipt_id,originalHistoryLine:r.original_history_line,originalEventTimestamp:r.original_event_ts,auditHistoryLine:n,reason:r.reason}])}function zf(e,t,n=[]){let i=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;i.set(o,Math.max(i.get(o)??0,a.auditHistoryLine))}let r=a=>QS(a)&&a.eventTimestamp!==void 0&&Lt(a.eventTimestamp,KS)<0&&(i.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!r(a)).map(a=>({item_id:a.itemId,history_line:a.line,...mt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:VS("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as e0}from"node:buffer";import{readFile as t0}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function n0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new g("History salvage cannot discard a potentially complete record with trailing corruption.",y.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("History salvage would conceal interior corruption or a malformed record.",y.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new g("History salvage requires complete history records before the invalid tail.",y.CONFLICT,{code:"history_salvage_refused"});return n}function i0(e){if($e(e))throw new g("Resolve history merge conflicts before salvage.",y.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,i,r=0;for(let[o,s]of e.split(`
|
|
53
53
|
`).entries()){if(!s.trim()){n+=s.length+1;continue}let c=n0(s);if(c===null){i===void 0&&(i=n,r=o+1),n+=s.length+1;continue}if(i!==void 0)throw new g("History salvage would discard a record or conceal interior corruption.",y.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=s.length+1}let a=bt(t);if(!a.ok||a.item_hash_version===void 0)throw new g("History salvage requires a nonempty verified prefix.",y.CONFLICT,{code:"history_salvage_refused",verification_errors:a.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:a.item_hash_version,prefix:i===void 0?e:e.slice(0,i),receipt:i===void 0?null:{first_invalid_line:r,discarded_bytes:Buffer.byteLength(e.slice(i)),discarded_sha256:xe(e.slice(i)),retained_entries:t.length}}}async function r0(e,t,n){if(!e.located)return{itemRaw:null,document:n};let i=await al(e.located,{schema:t.schema});return{itemRaw:i.raw,document:i.document??n}}async function Wf(e){let t;try{t=await t0(e)}catch(n){if(j(n))return null;throw n}if(!e0(t))throw new g("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",y.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function qf(e){let{subject:t,settings:n,options:i,author:r}=e;if([i.normalizeProvenance,i.auditOperation,i.auditContext,i.auditContextById,i.forceAuditEntry,i.mergeReceiptProof,i.mergeReceiptProofById].some(Boolean))throw new g("Tail salvage cannot be combined with other repair modes.",y.USAGE);let a=await Wf(t.historyPath);if(a===null)throw new g(`No history stream exists for ${t.id}.`,y.NOT_FOUND);await Ne({path:t.historyPath,scope:"project"});let o=i0(a),s=Xd(o.entries,o.entries.length-1),c=zd(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new g("History belongs to another item; salvage refused.",y.CONFLICT,{code:"history_salvage_refused"});let d=await r0(t,n,c),l=po({itemDocument:d.document,subjectId:t.id,author:r,force:i.force,settings:n}),u=o.itemHashVersion,m=i.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await re(e.pmRoot,t.id,n.locks.ttl_seconds,r,!!i.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Wf(t.historyPath),_=await ge(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=_?await B(_.itemPath):null;if(h!==a||w!==d.itemRaw)throw new g("History or item changed while waiting for salvage lock; retry.",y.CONFLICT);let v=nr({...Hd({hashAlgorithm:Re(o.entries.at(-1).hash_algorithm),nowIso:$(),author:r,op:"history_salvage",before:c,after:c,message:i.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await Ir({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
|
|
54
54
|
`}),l.push(...await K({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:$()}}import{realpath as Kf}from"node:fs/promises";import gs from"node:path";import Yf from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6d2870f-ebba-580a-85e9-3eb44e533d08")}catch{}})();function Gf(e,t){return t==="body"?e.body:e.metadata[t]}function a0(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function o0(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function Bf(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(i=>a0(e,i)))return t;let n=t.map(i=>e==="comments"?i:o0(i));return[...new Map(n.map(i=>[A(i),i])).values()]}function ys(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let i=new Set;return e.every(r=>{let a=t.findIndex((o,s)=>!i.has(s)&&ys(r,o));return a<0?!1:(i.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([i,r])=>Object.hasOwn(n,i)&&ys(r,n[i]))}function Jf(e,t){let n=new Set(t),i=[];for(let r=e.length-1;r>=0&&n.size>0;r-=1){let a=e[r],o=new Set;for(let c of ar(a.patch))o.add(sr(c.path)),c.from&&o.add(sr(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);i.push({index:r+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return i.reverse()}function s0(e,t,n){let i=Yf.compare(t,n);if(i.length===0)return;let r=new Set;for(let p of i)r.add(sr(p.path));let a=new Set([...r].filter(p=>ys(Bf(p,Gf(t,p)),Bf(p,Gf(n,p))))),o=new Set([...r].filter(p=>!a.has(p))),s=Jf(e,o),c=Jf(e,a),d=[...r].sort((p,h)=>p.localeCompare(h)),l=[...o].sort((p,h)=>p.localeCompare(h)),u=[...a].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:r.size,reconciled_fields:d,reverted_field_count:o.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function c0(e){try{return await Kf(e)}catch{return null}}async function d0(e){if(await c0(gs.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let i=Object.keys(n).sort();if(t.length!==i.length||t.some((a,o)=>a!==i[o]))return null;let r=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:r[a];return[At(o),xe(A(V(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function l0(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Kf(e.itemPath),i=[];for(let o of t){let s=await d0({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&i.push(s)}let r=new Set(i.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return i.length>0&&(a===void 0||a.length>0&&a.every(o=>r.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:i.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Vf(e,t,n,i){if(e===void 0)return;let{receipt:r,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:gs.relative(a,t.currentItemPath).split(gs.sep).join("/");if(!n||i.entriesRehashed!==0||i.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==r.item_path||r.operation===void 0||!await If(a,r.item_path,r.operation,t.currentItemRawBeforeLock))throw new g("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function u0(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),n=e.options.mergeReceiptProof?await pt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,i=n?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[];Lf(t,n,e.options.dryRun===!0);let r=e.options.mergeReceiptProof?await l0({proof:{...e.options.mergeReceiptProof,receipts:i},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new g(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let a=r?.trusted?i.filter(o=>r.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:a.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:a.map(oa)}}:e.options.auditContext}}function m0(e,t,n){let i=e.located?.itemPath??null,r=t.loadedItem,a=t.entries;if(!r)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=rr(r.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:tn(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:r.raw,loadedItem:r}}function p0(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function f0(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,i=Re(e.reanchorEntries.at(-1)?.hash_algorithm),r=tn(e.finalReplay,e.itemHashVersion,i),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(a),s=tn(n,e.itemHashVersion,i),c={hash_algorithm:i,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Yf.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(nr({...c,event_class:Nd(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function h0(e,t,n){let i=[];return e||i.push("history_repair_no_changes"),t>0&&i.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&i.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),i}async function ws(e,t,n){let{pmRoot:i,settings:r,typeRegistry:a}=await Xa(n.path),o=await Rl(i,e,r,a.type_to_folder);return t.salvageTail===!0?qf({pmRoot:i,subject:o,settings:r,typeRegistry:a,options:t,author:z(t.author,r.author_default)}):Au({pmRoot:i,subject:o,settings:r,typeRegistry:a,operation:"history-repair",options:t,transform:s=>g0({pmRoot:i,subject:o,options:t},s)})}function _0(e,t,n){let i=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(r=>r.record_hash_version!==void 0&&r.op==="merge_reconcile"&&A(r.context)===A(n));return e.forceAuditEntry===!0&&!i}async function g0(e,t){let{pmRoot:n,subject:i,options:r}=e,a=t.entries,o=t.verification,s=bt(a),c=r.normalizeProvenance?ku(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=Wd(c.entries),l=new Set(c.entries.map(P=>P.item_hash_version).filter(P=>P!==void 0)),u=or(c.entries,d),m=m0(i,t,d);await Vf(r.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=tn(f,d),h=!1;if(m.currentItemReplay!==null){let P=tn(m.currentItemReplay,d);h=!p.some((x,q)=>x===P[q])}let _=h&&m.currentItemReplay?s0(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await u0({options:r,pmRoot:n,subjectId:i.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,_0(r,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,I=!!r.dryRun,C=p0({message:r.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=f0({reanchorEntries:u.entries,changed:E,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:C,auditOperation:r.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),O=h0(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>Vf(r.mergeAbandonmentProof,m,o.ok,u),report:({verification:P,warnings:x})=>({id:i.id,dry_run:I,changed:E,history:{path:i.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:P.ok,verify_errors:P.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:r.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...O,...x])].sort((q,Se)=>q.localeCompare(Se)),generated_at:$()})}}function Ej(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function Sj(e,t){if(e.salvageTail===!0)throw new g("Tail salvage requires one explicit item ID; --all is not supported.",y.USAGE);let{pmRoot:n,settings:i,typeRegistry:r}=await Xa(t.path),a=[],o=await rt(n,i.item_format,r.type_to_folder,a,i.schema,{forceSourceScan:!0}),s=await Ut(n,o),c=e.normalizeProvenance?await Eu(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await ws(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(_=>`${f}:${_}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await Md(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_at:$()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="11486e17-e6da-5770-8621-f59a17bb4922")}catch{}})();var y0=new Set(yl),Xf=25,w0=be.join("runtime","telemetry","events.jsonl"),v0=be.join("runtime","telemetry","state.json"),b0=2500,k0=500,Zf=kl-3,E0=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function xs(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Is(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function An(e){return e.trim().toLowerCase()}function ks(e,t){let n=An(e),i=An(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Rs(e){try{return(await ht.stat(e)).isDirectory()}catch{return!1}}async function S0(e){let t=(await ht.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>ht.readdir(be.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>jn.some(a=>r.name.endsWith(a))).map(r=>be.parse(r.name).name)))}async function x0(e,t,n,i){let r=await Ne({path:e,scope:"project"}),a=t!=="_workspace"&&!i.has(t);if(!n.enabled&&!a)return{warnings:r,overThreshold:!1,classification:"live"};let o;try{o=await ht.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function I0(e,t,n){let i=be.join(e,"history");if(!await Rs(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ht.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),a=t.enabled?t.max_entries:null,o=[],s=[],c=[],d=[];for(let l of r){let u=be.join(i,l),m=l.slice(0,-6),f=await x0(u,m,t,n);o.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&d.push(m),f.overThreshold&&s.push(m)}return{count:r.length,warnings:[...o,...s.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:s,max_entries:a,tombstones:c,orphaned:d}}function Es(e,t){return be.relative(e,t).replaceAll("\\","/")}async function Qf(e,t){let n=[...new Set(Object.values(t))].sort((r,a)=>r.localeCompare(a)),i=[];for(let r of n){let a=be.join(e,r),o=[];try{o=await ht.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&j(s))continue;continue}for(let s of o)jn.some(c=>s.toLowerCase().endsWith(c))&&i.push(be.join(a,s))}return i.sort((r,a)=>Es(e,r).localeCompare(Es(e,a))),i}function R0(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function A0(e,t,n){let i=await Qf(e,t),r=[],a=[],o=[],s=[],c=Gt(F());for(let d of i){let l=Es(e,d),u;try{u=await ht.readFile(d,"utf8")}catch{r.push(l);continue}let m=$e(u);if(m){a.push({path:l,...m});continue}try{let f=vt(u,{format:$c(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:Zi(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function C0(e){let t=be.join(e,"history"),n=[],i=[],r=[],a=[],o=[],s=[];try{s=(await ht.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){R0(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await ht.readFile(be.join(t,c),"utf8")}catch{n.push(d);continue}let u=$e(l);if(u){i.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...Uf(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Hf(p,d,f+1))}catch{r.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:i,invalidJson:r,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function eh(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function T0(e,t,n,i,r,a){let o=await A0(e,t,n),s=await C0(e),c=Qi(o.formatVersions,Hn,Xi),d=fe(n),l=hr(a,x=>Dd(x,d),Gn()),u=await Kr(e),m=await Et(e),f=await uf(e,m),p=await mf(e,m,i,r),h=m===null?null:await dn(m),_=await pt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(_.durable_receipt_ids),v=zf(s.mergeReceiptReferences,w,s.mergeReceiptDispositions),E=v.missing,k=_.receipts.filter(x=>x.state==="pending"),{pendingDecisions:I,lossless:C}=Rn(k),S=h?.status==="missing"&&h.missing_keys.length===5&&h.drifted_keys.length===0,b=[...o.unreadable.map(x=>`integrity_item_unreadable:${x}`),...o.conflictMarkers.map(x=>`integrity_item_conflict_marker:${x.path}:L${x.line}`),...o.parseFailures.map(x=>`integrity_item_parse_failed:${x}`),...s.unreadable.map(x=>`integrity_history_unreadable:${x}`),...s.conflictMarkers.map(x=>`integrity_history_conflict_marker:${x.id}:L${x.line}`),...s.invalidJson.map(x=>`integrity_history_invalid_json:${x.id}:L${x.line}`),...c.outdated.map(x=>`integrity_item_outdated_format_version:${x}`),...c.ahead.map(x=>`integrity_item_ahead_format_version:${x}`),...eh(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...h!==null&&h.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${h.missing_keys.length+h.drifted_keys.length}`]:[],...p.warnings,...f.warnings,...I.length>0?[`merge_decisions_unreviewed:${I.length}`]:[],...C.length>0?[`merge_receipts_pending:${C.length}`]:[],...pf({invalidEvidenceCount:_.invalid_evidence_count,missingHistoryReferenceCount:E.length})],O=[...new Set(b)].sort((x,q)=>x.localeCompare(q)),P=O.filter(x=>!x.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:P.length===0?"ok":"warn",ok:P.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:h===null||h.status==="ok"?0:h.missing_keys.length+h.drifted_keys.length,merge_fence:p.count,ignored_merge_artifacts:f.rules.length,pending_merge_decisions:I.length,lossless_merge_receipts:C.length,invalid_merge_receipt_evidence:_.invalid_evidence_count,missing_merge_receipt_history_references:E.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:je(l.relations,Tu)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:h===null?null:{...h,required:r},merge_fence:p.audit,ignored_merge_artifacts:f.rules,pending_merge_decision_items:[...new Set(I.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),lossless_merge_receipt_items:[...new Set(C.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),invalid_merge_receipt_evidence_details:_.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:_.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:E.slice(0,fo),missing_merge_receipt_history_reference_details_truncated:E.length>fo}},warnings:O,gitWorkspaceRoot:m,pendingMergeReceipts:k}}function $0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function D0(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:$0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function O0(e,t){return Y(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function P0(e){let t=Y(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function L0(e){return Y(e.reason)??Y(e.error)??Y(e.message)}function vs(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let i=(e.name??"").localeCompare(t.name??"");return i!==0?i:(e.id??"").localeCompare(t.id??"")}function N0(e){let t=[],n=[],i=[];e.forEach((a,o)=>{let s=O0(a.definition,o),c=P0(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){i.push({layer:a.layer,name:a.name,id:s,status:c,reason:L0(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(vs),n.sort(vs),i.sort(vs);let r=[...i.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:i,applied_count:t.length,pending_count:n.length,failed_count:i.length},warnings:r}}function th(e,t,n,i,r,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>Is(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=d.map(ri).filter(_=>_!==void 0),h=Jo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(i.failed_count>0||i.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Li.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:i.failed_count,migration_pending_count:i.pending_count,managed_state_warning_count:r,managed_extension_entries_count:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function M0(e,t,n){let i=await es(Ge(e)),r=await Be({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(S=>D0(S)),o=await vu(r.loaded,Ge(e)),s=await Je({...r,loaded:r.loaded}),[c,d]=await Promise.all([he(r.roots.project),he(r.roots.global)]);await Qo(e,s.registrations.migrations);let l=N0(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(S=>An(S.name))),f=new Set(d.state.entries.map(S=>An(S.name))),p=[...new Map(r.loaded.filter(S=>!(S.layer==="project"?m:f).has(An(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let O=`${S.layer}:${S.name}`,P=`${b.layer}:${b.name}`;return O.localeCompare(P)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),_=p.filter(S=>ks(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!ks(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],E=[...i.warnings,...r.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=hi(E),I=_i(),C=th(E,r.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,_,w);return{check:{name:"extensions",status:E.length===0?"ok":"warn",ok:E.length===0,details:{...r,loaded:a,warnings:E,activation:u,author_manifest:i,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:I,capability_guidance:k,host_version_census:o}},warnings:E}}function Ss(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=$u(e,Xf);return{values:n.values,truncated:n.truncated,total:e.length}}function ca(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function j0(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return y0.has(e)?e:null}function da(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function nh(e){let t=0,n=0,i=0,r=0,a=0;for(let o of e.split(`
|
|
55
55
|
`)){let s=o.trim();if(s.length!==0){i+=1;try{let c=JSON.parse(s);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,a=Math.max(a,d),d>=Zf&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:a}}function F0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function U0(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function H0(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Ka().telemetry_disabled?void 0:{attempted:!0,...await ih(n)}}function z0(e,t,n){let i=[];if(t.invalidRows>0&&i.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return i;let r=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!r||a>r),s=!r,c=t.validEntries>=k0;return(o||s||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function W0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function q0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>bl?[`telemetry_schema_version_behind:${t}`]:[]}function G0(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,i=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&r&&(!i||r>=i)?[`telemetry_otel_export_failing:${n}`]:[]}function B0(){return{...Ka(),pm_no_telemetry:ca("PM_NO_TELEMETRY"),telemetry_otel_disabled:ca("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ca("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:j0()}}function J0(e,t){return e.telemetry.enabled&&t.validEntries>0}function V0(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function ih(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(b0)});return{probe_url:da(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of E0){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:da(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function K0(e,t){let n=ji(process.cwd()),i=be.join(n,w0),r=be.join(n,v0),a=await B(i),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?nh(a):F0(),d=await B(r),{runtimeState:l,stateParseFailed:u}=U0(d),m=e.telemetry.endpoint.trim(),f=da(m),p=await H0(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...z0(e,c,l),...W0(p),...q0(p),...G0(e,l));let _=J0(e,c),w=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:i,queue_exists:o,queue_entries:c.validEntries,queue_draining:V0(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Zf,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:B0()}},warnings:h}}async function Y0(e){let t;try{t=await Qu(e)}catch(i){let r=i instanceof Error?i.message:String(i);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function X0(e){let t="metadata",n=e.items,i=await Ut(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(r.length>0){n=await rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Ut(e.pmRoot,n),a=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,E)=>v.localeCompare(E));let w=new Set(a);o=r.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=i,_=[...s.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:r.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function Z0(e,t){let n=ur(e),i=qn(n.settings),r=fr(n.settings,t),a=i.active?Mt(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(i.active&&r.active)}}function Q0(){return{refreshed:[],skipped:[],warnings:[]}}async function ex(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?Q0():gl(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function tx(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&an(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function nx(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,i)=>n.localeCompare(i))}function ix(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function rh(e,t){let n=t.providerResolution.active?.name??null,i=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Ba(n,e.search?.provider??null),vector_store_active:i,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Ba(i,e.vector_store?.adapter??null)}}function rx(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function ax(e,t,n){return e.enabled&&n.length>0&&t}async function ox(e,t,n,i,r){let a=Z0(t,e),o=await on(e),s=a.semanticRuntimeAvailable?Za(n,o.entries):[],c=await ex({pmRoot:e,snapshot:a,refreshPolicy:i,staleBefore:s}),d=await on(e),l=a.semanticRuntimeAvailable?Za(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=tx({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=nx({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Ss(s,r),h=Ss(l,r),_=ax(i,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:rx(i),...rh(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:Xf,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:ix(i,a.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function sx(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function ah(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new g("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new g("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var cx=new Set(["extensions","locks","search"]);function dx(e){let t=new Set(bc.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(kc));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of cx)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,a)=>r.localeCompare(a)),optionalDirs:[...n].sort((r,a)=>r.localeCompare(a)),optionalDirSet:n}}async function lx(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:a}=dx(t),o=[],s=[],c=[];for(let d of[...i,...r]){let l=be.join(e,d);c.push(...await Ne({path:l,scope:"project"})),!await Rs(l)&&(a.has(d)?s.push(d):o.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function oh(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,i=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||i)&&e.full!==!0,skipDrift:(e.skipDrift===!0||i)&&e.full!==!0,skipVectors:(e.skipVectors===!0||i)&&e.full!==!0}}async function ux(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?it(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function bs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function mx(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function px(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function fx(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var As=e=>e.unknown_event_count??0,Cs=e=>e.actionable_unknown_event_count??As(e);function hx(e,t,n,i,r,a){let o=As(i),s=Cs(i),c=o>0,d=s>0,l=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:i}:{},...l?{stale_in_progress:r}:{},...a.outcomes.length>0?{provenance_resolver_outcomes:a.outcomes}:{},...a.invalid_values.length>0?{provenance_invalid_values:a.invalid_values}:{},provenance_sample:a.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function sh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function _x(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function gx(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function yx(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function ch(e){let t=new Map;for(let[i,r]of Object.entries(e.remediationSources))for(let a of r)t.has(a)||t.set(a,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let r=t.get(i)??"integrity",a=ko(i)?.code??Is(i),o=n.get(r)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=ri(i)??(a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a]),d=xs(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:a,check:r,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function wx(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function vx(e){for(let t of e.checks){let n=Eo(e.remediationSources[t.name]);wx({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function bx(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),r=new Map;for(let o of e.pendingMergeReceipts){let s=r.get(o.item_id)??[];s.push(o),r.set(o.item_id,s)}let a=[];for(let o of n){if(i.has(o))continue;let s=r.get(o);if(!(!s||s.length===0))try{await ws(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),a.push(o)}catch{}}return[...new Set(a)].sort((o,s)=>o.localeCompare(s))}function kx(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(i=>i.startsWith("history_drift_hash_mismatch:")?!n.has(i.slice(i.indexOf(":")+1)):!0),...t.map(i=>`history_drift_merge_receipt:${i}`)].sort((i,r)=>i.localeCompare(r)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function dh(e,t={}){let n=M(process.cwd(),e.path);await te(n);let i=Bt(n),{settings:r,warnings:a}=await Vd(n),o=[...new Set(a)],s=H(r,F()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=ah(t),m=await lx(n,s,c),f=sx(r),p=await K0(r,{checkTelemetry:t.checkTelemetry===!0}),h=await M0(n,r,!!e.noExtensions),_=oh(t),w=[],v=await ux({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Rr(fe(r.schema),v),I=[...(await Hu({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ue=>ue.startsWith("agent_guidance_")),...f,...Ar(k)],C=_.skipDrift?{warnings:[]}:await qd({pmRoot:n,settings:r,itemIds:v.map(ue=>ue.id),commandLabel:"health"}),S=await I0(n,r.history.compact_policy,await S0(n)),b=await Qn(n,20,t.verboseAuthorEvents===!0),O=Cs(b),P=O>0?[`history_unknown_author_events:${O}`]:[],x=sh(await wl(n,v,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),q=await Iu(n),Se=q.warnings,_e=await Y0(n),pe=_.skipIntegrity&&!l?{...bs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await T0(n,s.type_to_folder,r.schema,r,l,v),Le=_.skipDrift?bs("history_drift"):await X0({pmRoot:n,items:E,settings:r,typeRegistry:s,itemReadWarnings:w}),Di=[...new Set(w)],Nn=await bx({gitWorkspaceRoot:pe.gitWorkspaceRoot,pendingMergeReceipts:pe.pendingMergeReceipts,historyDriftCheck:Le,global:e});kx(Le,Nn);let U=_.skipVectors?bs("vectorization"):await ox(n,r,E,u,t.verboseStaleItems===!0),G=[mx(i,r,o),px(m,c),fx(I,k),p.check,h.check,hx(v,r,S,b,x.scan,q),_e.check,pe.check,Le.check,U.check],Oi=_x({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Di,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U}),Pi=yx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Di,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U});vx({checks:G,remediationSources:Pi,historyDriftedCount:gx(Le),overThresholdCount:S.over_threshold.length});let Aa=Oi.filter(ue=>!xs(ue,l)),Ca=ch({warnings:Oi,checks:G,remediationSources:Pi,requireMergeDrivers:l}),ag=new Set(Ca.filter(ue=>ue.severity==="gate_failing").map(ue=>ue.check)),og=new Set(Ca.map(ue=>ue.check));for(let ue of G)ue.ok=!ag.has(ue.name),og.has(ue.name)&&(ue.status="warn");let sg={ok:Aa.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Aa.length>0?y.GENERIC_FAILURE:0},checks:G,warnings:Oi,findings:Ca,failed_because:Aa,generated_at:$()};return go(sg,t,_.summaryMode)}var S1={buildHierarchyIntegrityWarnings:eh,buildExtensionHealthTriageSummary:th,buildHealthFindings:ch,buildCapabilityContractMetadata:_i,buildStaleInProgressHealthSummary:sh,buildVectorizationProviderDetails:rh,collectUnknownCapabilityGuidance:hi,isAdvisoryHealthWarning:xs,isDirectory:Rs,isExpectedUnmanagedExtension:ks,listItemDocumentPaths:Qf,normalizeEndpointForDisplay:da,normalizeExtensionNameForMatch:An,parseTelemetryQueue:nh,probeTelemetryEndpointHealth:ih,projectHealthResult:go,resolveActionableUnknownAuthorEventCount:Cs,resolveHealthSkipPolicy:oh,resolveUnknownAuthorEventCount:As,resolveVectorRefreshPolicy:ah,selectStaleItemDetail:Ss,summarizeHealthCheckDetails:ho,summarizeExtensionList:ti,summarizeRecordList:je,summarizeStringList:W,telemetryEnvFlagEnabled:ca,warningCode:Is};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function lh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Al(e,t).ok)return{reason:"unverified_history"};let i=ir(),r={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(i.metadata.status));i=Yd(i,o.patch,a+1,o.op),n.has(String(i.metadata.status))?s||(r=["create","close","cancel","update","update_audit"].includes(o.op)&&wt(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):r={reason:"no_proven_transition"}}return r}function uh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function mh(e,t,n,i,r){let a=uh(n),o=t.filter(d=>a.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of i?o:[]){let l;try{let u=await nt(Ot(e,d.id),d.id),{body:m,...f}=d;l=lh(u,{metadata:f,body:m},a)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}s.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,r).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>r,closure_history_inspected:i,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,r),closure_timestamp_residual_truncated:c.length>r,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function ph(e,t){let n=M(process.cwd(),t.path),i=await T(n),r=fe(i.schema);await at({pmRoot:n,settings:i,id:e.item_id,op:"update",author:z(t.author,i.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await nt(Ot(n,a.metadata.id),a.metadata.id),s=uh(r),c=lh(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new g("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",y.GENERIC_FAILURE);return a.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function Ex(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function fh(e){return`${e.item_id} ${e.link_kind}`}function hh(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Ex(r.classification,i.classification),r.owners.set(fh(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[fh(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function _h(e,t,n,i,r=40){let a=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,o=new Map(t.map(d=>[d.path,d])),s={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=hh(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=er(f.status,i)??f.status;i.terminal_statuses.has(p)?(u.push(f),p===i.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,a),items_truncated:d.items.length>a}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import Cn from"node:fs/promises";import Tn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function Sx(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let a;try{a=await Cn.readdir(Tn.join(e,r))}catch{return}for(let o of a)for(let s of jn)if(o.toLowerCase().endsWith(s)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-s.length)});break}})),i.sort((r,a)=>r.relativePath.localeCompare(a.relativePath))}function xx(e,t){let{id:n,relativePath:i,liveItemIds:r,out:a}=e,o=$e(t);if(o){a.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=Ix(e,t);s!==null&&(s.op==="delete"&&r.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function Ix(e,t){let{id:n,relativePath:i,out:r}=e,a=null,o=!1,s=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of s){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)return r.unparseable.push({id:n,path:i,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return a}function Ts(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function Rx(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await Cn.readdir(Tn.join(e,"history"))}catch{return n}for(let r of i.sort((a,o)=>a.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await Cn.readFile(Tn.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ts("history stream",o)});continue}xx({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},a)}return n}function gh(e){let t=$e(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function Ax(e){let t=[],n=0,i=null;try{i=await B(Bt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Ts("configuration file",a)})}if(i!==null){n+=1;let a=gh(i);a!==null&&t.push({path:"settings.json",detail:a})}let r;try{r=await Cn.readdir(Tn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of r.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await Cn.readFile(Tn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Ts("configuration file",c)});continue}let s=gh(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function yh(e,t,n,i={}){let r=await Sx(e,n),a=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Tn.join(e,u.relativePath);return vt(await Cn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Rx(e,a),l=await Ax(e);return{item_files_on_disk:r.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import nc from"node:fs/promises";import{realpathSync as HI}from"node:fs";import{execFile as zI}from"node:child_process";import Ee from"node:path";import{promisify as WI}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var Cx=["metadata","resolution"],$s=["metadata","resolution","estimates","timestamps","lifecycle"],Tx="completed";function Ds(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function wh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function vh(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=wh(n.close_reason)??Tx;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${Ds(i)}`,gate:"resolution"})}return t}function bh(e){let t=[];for(let n of e){let i=wh(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${Ds(i)}`,gate:"metadata"})}return t}function kh(e,t){return e.map(n=>{let i=Bd(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function Eh(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Sh(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${i} ${n.item_id} --remove ${Ds(n.path)}`})}return t}function xh(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new g(`--fix-scope values must not be empty. Supported values: ${$s.join(", ")}.`,y.USAGE);return new Set(Cx)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if($s.includes(r)){n.add(r);continue}throw new g(`Unknown --fix-scope value "${i}". Supported values: ${$s.join(", ")}.`,y.USAGE)}return n}function Ih(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function Ei(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var $x=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function Dx(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=$x.exec(n);if(!i)return null;let r=i[1],a=r.toUpperCase(),o=r.slice(0,r.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(r.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${a}`)||d.includes(`ISSUE CODE \`${a}\``)||d.includes(`\`${a}\``)||d.includes(`[${a}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(o.toUpperCase())||l?a:null}function Rh(e){return typeof e=="string"&&e.trim().length>0}function Ox(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,i=new Map;for(let o of e){let s=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(d=>d!==s&&t.has(d)));n.set(s,c);for(let d of c){let l=i.get(d)??[];l.push(s),i.set(d,l)}}let r=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<r.length;o+=1)for(let s of i.get(r[o])??[]){let c=n.get(s);c.delete(r[o]),c.size===0&&(a.add(s),r.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function Ah(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||Rh(r.duplicate_of))continue;let a=Dx(r.title,{...t,evidenceText:r.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===r.id)||o.push({id:r.id,title:r.title,parent:Rh(r.parent)?r.parent.trim():null,derivations:(r.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==r.id.toLowerCase())})}let i=[];for(let[r,a]of n){if(a.length<2)continue;let o=Ox(a);if(o.length<2)continue;let s=[...o].sort((c,d)=>c.id.localeCompare(d.id));i.push({code:r,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return i.sort((r,a)=>r.code.localeCompare(a.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function Ch(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,a)=>r.localeCompare(a))){let r=t.get(i),a={};for(let o of[...r.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=r.get(o);n[i]=a}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function Th(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function $h(e,t,n=3){let i=Number.isFinite(n)&&n>=1?Math.floor(n):3,r=new Map;for(let a of t){let o=Th(a);if(o.length===0)continue;let s=r.get(o);s?s.push(a):r.set(o,[a])}return e.map(a=>{if(a.includes(",")||a.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:a,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(r.get(Th(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Dh(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var Px=/^[a-z][a-z0-9+.-]+:\/\//i;function Si(e){return Px.test(e.trim())}import Lx from"node:fs/promises";import ke from"node:path";import{glob as Nx}from"tinyglobby";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var Mx=["path","scope","note"],jx=["pattern","glob","path","scope","note"],Fx=["path"],Ux=["from","to"],Hx=new Set(["note","scope"]);function Ph(e){let t=e??"project";if(!Ta.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Ta.join(", ")} (default: project).`,y.USAGE);return t}function Os(e){if(e.startsWith("```")||e.includes(`
|
|
@@ -62,4 +62,4 @@ ${a}`,y.GENERIC_FAILURE)}}function Ra(e){return typeof e.tag=="string"&&e.tag.tr
|
|
|
62
62
|
`);oe(e.progressEnabled,"writing keyword artifacts"),await Z(t,`${JSON.stringify(e.manifest,null,2)}
|
|
63
63
|
`),await Z(n,`${r}
|
|
64
64
|
`);let a=[];if(e.mode!=="keyword")try{oe(e.progressEnabled,"writing vectorization status ledger"),await _l(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 kW(e,t){let n=eC(e.mode),i=QA(e),r=e.full===!0;oe(i,`start mode=${n}`);let a=M(process.cwd(),t.path);await te(a);let o=ur(await T(a)).settings,s=null;try{s=await re(a,Kd,o.locks.ttl_seconds,z(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof g&&c.exitCode===y.CONFLICT?new g("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",y.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=iC(o),d=rC(o),l=lC({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;oe(i,"loading item corpus");let m=await uC({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;oe(i,`loaded_items=${h.length}`);let _=$(),w=dC(u,_,h),v=$i.join(a,pc),E=$i.join(a,fc),k=u==="keyword"?await _c(a,p,o.schema,f):h,I=[],C={},S=null,b=cC(u);if(u==="keyword"&&await mC({pmRoot:a,settings:o,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let x=await wC({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:k,forceFullSemantic:r,reindexWarnings:f,semanticWarnings:I,semanticSummary:b,progressEnabled:i});k=x.documentsForKeywordArtifacts,C=x.vectorizationLedgerEntries,S=x.vectorizationEmbeddingMetadata}let O=await vC({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:C,vectorizationEmbeddingMetadata:S,progressEnabled:i}),P=[...await K({path:v,scope:"project",op:"reindex:manifest"}),...await K({path:E,scope:"project",op:"reindex:embeddings"}),...await Gi({mode:u,total_items:h.length})];return oe(i,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:pc,embeddings:fc},warnings:[...f,...I,...O,...P],generated_at:_}}finally{await s?.()}}export{L as a,we as b,Ke as c,ln as d,Qa as e,Pl as f,jt as g,eo as h,hg as i,io as j,ro as k,jl as l,mn as m,Vn as n,oo as o,Pg as p,ql as q,Kn as r,Bl as s,kr as t,so as u,Jl as v,Vl as w,Kl as x,um as y,Mg as z,LC as A,Zl as B,Ug as C,tT as D,iv as E,LD as F,jD as G,FD as H,oi as I,UD as J,HD as K,zD as L,WD as M,qD as N,GD as O,BD as P,JD as Q,VD as R,KD as S,YD as T,Yo as U,rs as V,s$ as W,Hu as X,qg as Y,ru as Z,pT as _,Qn as $,fT as aa,Xg as ba,Zg as ca,hT as da,Qg as ea,Lh as fa,vT as ga,uu as ha,Mh as ia,jF as ja,FF as ka,ei as la,xr as ma,pu as na,fu as oa,hu as pa,_u as qa,vu as ra,ku as sa,Eu as ta,Iu as ua,At as va,JN as wa,VN as xa,KN as ya,YN as za,rM as Aa,If as Ba,oa as Ca,AM as Da,pt as Ea,Lf as Fa,CM as Ga,TM as Ha,KS as Ia,QS as Ja,Uf as Ka,wy as La,Au as Ma,ws as Na,Ej as Oa,Sj as Pa,Rr as Qa,Ar as Ra,dh as Sa,S1 as Ta,lh as Ua,mh as Va,ph as Wa,_h as Xa,yh as Ya,yI as Za,wI as _a,WF as $a,qF as ab,GF as bb,BF as cb,bI as db,kI as eb,EI as fb,JF as gb,Uh as hb,xI as ib,Hh as jb,Fs as kb,Wh as lb,II as mb,RI as nb,AI as ob,Ws as pb,qs as qb,rU as rb,aU as sb,oU as tb,aR as ub,gH as vb,T_ as wb,Ai as xb,O_ as yb,P_ as zb,L_ as Ab,ac as Bb,pA as Cb,ez as Db,Ez as Eb,$z as Fb,V_ as Gb,K_ as Hb,Y_ as Ib,tW as Jb,fW as Kb,hW as Lb,_W as Mb,kW as Nb};
|
|
65
|
-
//# sourceMappingURL=chunk-
|
|
65
|
+
//# sourceMappingURL=chunk-C2GLO7HU.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{r as q,s as V}from"./chunk-
|
|
1
|
+
import{r as q,s as V}from"./chunk-I4X6AKOO.js";import{m,s as M,u as k}from"./chunk-6VDRAJYX.js";import{Fa as O,Md as z,R as x,W as g,pd as N,sd as D,vd as j}from"./chunk-6L4KKRK7.js";import{D as _,H as L,y as S,z as C}from"./chunk-7SZPZOIC.js";import{constants as p}from"node:fs";import{lstat as A,mkdir as I,open as P}from"node:fs/promises";import h from"node:path";(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="5434ff6f-95af-5983-88cb-fd360d95cb9e")}catch{}})();function E(i,e){if(typeof i!="string"||i.trim().length===0)throw new TypeError(`Relationship event ${e} must be non-empty`);return i.trim()}function $(i,e){let t=e.require(i.kind),n=t.direction==="undirected"?[i.source,i.target].sort().join("\0"):`${i.source}\0${i.target}`;return`${t.kind}\0${n}`}function Q(i){return Object.freeze({...i,...i.payload===void 0?{}:{payload:Object.freeze(structuredClone(i.payload))}})}function U(i,e,t,n){let r=t.require(i.kind),o=n.outgoingOne.get(`${r.kind}\0${i.source}`);if(o!==void 0&&o!==e)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=n.incomingOne.get(`${r.kind}\0${i.target}`);if(s!==void 0&&s!==e)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let c=$(i,t),a=n.identities.get(c);if(a!==void 0&&a!==e)throw new TypeError(`Relationship edge already active: ${c}`)}function Y(i){let e=new Map;for(let t of i)t.action==="remove"?e.delete(t.relationshipId):e.set(t.relationshipId,t.edge);return e}function X(i,e,t){if(i.expectedVersion!==void 0&&i.expectedVersion!==e)throw new TypeError(`Relationship event version conflict: expected ${i.expectedVersion}, current ${e}`);let n=E(i.eventId,"eventId");if(t.has(n))throw new TypeError(`Relationship event already exists: ${n}`);if(i.action!=="add"&&i.action!=="remove"&&i.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${i.action}`);if(!Number.isFinite(Date.parse(i.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:n,relationshipId:E(i.relationshipId,"relationshipId"),author:E(i.author,"author"),timestamp:new Date(i.timestamp).toISOString()}}function Z(i,e,t,n,r,o){let s=t.has(e);if(i.action==="add"&&s)throw new TypeError(`Relationship is already active: ${e}`);if(i.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${e}`);if(i.action==="remove")return;if(!i.edge)throw new TypeError(`Relationship ${i.action} event requires an edge`);let c=typeof i.edge.source=="string"?i.edge.source.trim():"",a=typeof i.edge.target=="string"?i.edge.target.trim():"";if(!n.has(c)||!n.has(a))throw new TypeError(`Relationship endpoint not found: ${c} -> ${a}`);let d=new g([c,a],[i.edge],r).edges()[0];return U(d,e,r,o),Q(d)}var T=class{#t;#i;#n=[];#o=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(e,t={}){this.#t=new Set([...e].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean)),this.#i=t.registry??x()}get version(){return this.#n.length}events(){return Object.freeze([...this.#n])}*stream(e={}){let t=e.fromVersion??1,n=e.toVersion??this.version,r=e.batchSize??100;if(!Number.isInteger(t)||t<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(n)||n<0||n>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${n}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(t>n+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let o=t-1;o<n;o+=r)yield Object.freeze(this.#n.slice(o,Math.min(o+r,n)))}project(e,t,n={}){if(typeof t!="function")throw new TypeError("Relationship event projection requires a reducer");let r=e,o=0,s;for(let c of this.stream({...n,batchSize:256}))for(let a of c)r=t(r,a),o+=1,s=a;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(n.fromVersion??1)-1),processed:o,...s===void 0?{}:{asOf:s.timestamp}})}#s(e,t){let n=this.#i.require(t.kind);this.#r.identities.set($(t,this.#i),e),n.outgoing==="one"&&this.#r.outgoingOne.set(`${n.kind}\0${t.source}`,e),n.incoming==="one"&&this.#r.incomingOne.set(`${n.kind}\0${t.target}`,e)}#a(e){let t=this.#i.require(e.kind);this.#r.identities.delete($(e,this.#i)),t.outgoing==="one"&&this.#r.outgoingOne.delete(`${t.kind}\0${e.source}`),t.incoming==="one"&&this.#r.incomingOne.delete(`${t.kind}\0${e.target}`)}append(e){let t=X(e,this.version,this.#o),n=this.#e.get(t.relationshipId),r=Z(e,t.relationshipId,this.#e,this.#t,this.#i,this.#r),o=Object.freeze({eventId:t.eventId,relationshipId:t.relationshipId,action:e.action,...r===void 0?{}:{edge:r},author:t.author,timestamp:t.timestamp,...e.reason?.trim()?{reason:e.reason.trim()}:{},sequence:this.version+1});return this.#n.push(o),this.#o.add(t.eventId),n&&this.#a(n),e.action==="remove"?this.#e.delete(t.relationshipId):(this.#e.set(t.relationshipId,r),this.#s(t.relationshipId,r)),o}snapshot(e={}){if(e.atVersion!==void 0&&e.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let t;if(e.atTimestamp!==void 0){let o=Date.parse(e.atTimestamp);if(!Number.isFinite(o))throw new TypeError("Relationship snapshot timestamp must be valid");t=this.#n.filter(s=>Date.parse(s.timestamp)<=o)}else{let o=e.atVersion??this.version;if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship snapshot version out of range: ${o}`);t=this.#n.slice(0,o)}let n=Y(t),r=new g(this.#t,n.values(),this.#i);return Object.freeze({version:t.at(-1)?.sequence??0,...t.at(-1)?{asOf:t.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(e){if(!Number.isInteger(e.limit)||e.limit<1)throw new TypeError("Relationship event page limit must be positive");let t=N("relationship-events",{order:"append-sequence"}),n=e.cursor===void 0?this.version:Number(D(e.cursor,t).snapshot);if(!Number.isSafeInteger(n)||n<0||n>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=j(this.#n.slice(0,n),{cursor:e.cursor,fingerprint:t,limit:e.limit,readId:o=>o.eventId,snapshot:String(n)});return{version:n,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},ee="relationship-event-store",W=p.O_NOFOLLOW;function w(i){return z(i,ee,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function f(i,e="relationships/events.jsonl"){let t=h.resolve(i),n=h.resolve(t,e),r=h.relative(t,n);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${h.sep}`)||h.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await I(t,{recursive:!0}),(await A(t)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let o=t;for(let s of r.split(h.sep)){o=h.join(o,s);try{if((await A(o)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(_(c))break;throw c}}return n}async function y(i,e,t){let n=new T(e,{registry:t}),r,o;try{o=await P(i,p.O_RDONLY|W),r=await o.readFile("utf8")}catch(c){if(_(c))return{log:n,raw:""};throw c}finally{await o?.close()}let s=r.split(`
|
|
2
2
|
`);for(let c=0;c<s.length;c+=1){let a=s[c].trim();if(!a)continue;let d;try{d=JSON.parse(a)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${c+1}`)}if(d.sequence!==n.version+1)throw new TypeError(`Invalid relationship event sequence at line ${c+1}`);n.append({eventId:d.eventId,relationshipId:d.relationshipId,action:d.action,...d.edge===void 0?{}:{edge:d.edge},author:d.author,timestamp:d.timestamp,...d.reason===void 0?{}:{reason:d.reason},expectedVersion:n.version})}return{log:n,raw:r}}function te(i,e,t,n){let r=Date.parse(e.timestamp),o;return e.action!=="remove"&&e.edge!==void 0&&(o=new g(t,[e.edge],n).edges()[0]),i.eventId===e.eventId.trim()&&i.relationshipId===e.relationshipId.trim()&&i.action===e.action&&i.author===e.author.trim()&&Number.isFinite(r)&&i.timestamp===new Date(r).toISOString()&&i.reason===(e.reason?.trim()||void 0)&&O(i.edge)===O(o)}var F=class i{#t;#i;#n;#o;#e;constructor(e,t,n,r){this.#t=e.pmRoot,this.#i=t,this.#n=e.registry,this.#o=n,this.#e=r}static async open(e){let t=Object.freeze([...e.nodes]),n=await f(e.pmRoot,e.relativePath),r=await w(e.pmRoot);try{await f(e.pmRoot,n);let{log:o}=await y(n,t,e.registry);return new i(e,t,n,o)}finally{await r()}}get path(){return this.#o}async currentVersion(){return this.#e=await this.#r(),this.#e.version}async append(e){let t=await w(this.#t);try{let n=await f(this.#t,this.#o),{log:r}=await y(n,this.#i,this.#n),o=r.append(e);await I(h.dirname(n),{recursive:!0}),await f(this.#t,n);let s=await P(n,p.O_APPEND|p.O_CREAT|p.O_WRONLY|W);try{await s.appendFile(`${JSON.stringify(o)}
|
|
3
3
|
`,"utf8")}finally{await s.close()}return this.#e=r,o}finally{await t()}}async appendBatch(e,t={}){let n=await w(this.#t);try{let r=await f(this.#t,this.#o),{log:o,raw:s}=await y(r,this.#i,this.#n),c=o.version,a=new Map(o.events().map(l=>[l.eventId,l])),d=[],R=[];for(let l of e){let u=l.eventId.trim(),v=a.get(u);if(v!==void 0){if(t.existingEventPolicy==="skip_identical"&&te(v,l,this.#i,this.#n)){R.push(v.eventId);continue}if(t.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${u}`)}let b=o.append(l);a.set(b.eventId,b),d.push(b)}if(d.length>0){let l=s.length===0||s.endsWith(`
|
|
4
4
|
`)?s:`${s}
|
|
5
5
|
`;await I(h.dirname(r),{recursive:!0}),await f(this.#t,r),await L(r,`${l}${d.map(u=>JSON.stringify(u)).join(`
|
|
6
6
|
`)}
|
|
7
7
|
`)}return this.#e=o,Object.freeze({version_before:c,version_after:o.version,appended:Object.freeze(d),skipped_event_ids:Object.freeze(R)})}finally{await n()}}async snapshot(e={}){return this.#e=await this.#r(),this.#e.snapshot(e)}async page(e){return this.#e=await this.#r(),this.#e.page(e)}async*stream(e={}){this.#e=await this.#r(),yield*this.#e.stream(e)}async project(e,t,n={}){return this.#e=await this.#r(),this.#e.project(e,t,n)}async#r(){let e=await w(this.#t);try{let t=await f(this.#t,this.#o);return(await y(t,this.#i,this.#n)).log}finally{await e()}}};(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function K(i){return[...i].sort().join("\0")}function ie(i,e,t){let n=i.successors.get(e);n?n.push(t):i.successors.set(e,[t]);let r=i.predecessors.get(t);r?r.push(e):i.predecessors.set(t,[e])}function G(i,e,t,n,r){let o=e.resolve(r);if(o?.ordering!==!0)return;let s=M(n),c=s===void 0?void 0:i.canonicalIds.get(s.toLowerCase());if(c===void 0)return;let a=(o.precedence??"source_before_target")==="source_before_target";ie(i,a?t:c,a?c:t)}function ne(i,e){let t={successors:new Map,predecessors:new Map,canonicalIds:new Map},n=i.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of n){let o=r.id.trim();t.canonicalIds.set(o.toLowerCase(),o)}for(let r of n){let o=r.id.trim();G(t,e,o,r.blocked_by,"blocked_by");for(let s of r.dependencies??[])typeof s!="object"||s===null||G(t,e,o,s.id,typeof s.kind=="string"?s.kind:"related")}for(let r of[t.successors,t.predecessors])for(let o of r.values())o.sort();return t}function re(i,e){let t=new Set([e]),n=[e];for(;n.length>0;){let r=n.pop();for(let o of[i.successors,i.predecessors])for(let s of o.get(r)??[])t.has(s)||(t.add(s),n.push(s))}return t}function oe(i,e){let t=new Map;for(let n of e){let r=(i.successors.get(n)??[]).filter(o=>e.has(o));r.length>0&&t.set(n,r)}return t}function H(i,e,t){let n=ne(i,e),r=n.canonicalIds.get(t.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:t};let o=oe(n,re(n,r));return{cycles:q(o).filter(s=>s.includes(r)),successors:o,canonical:r}}function se(i,e,t){let n=new Set(e),r=n.has(t)?t:e[0];if(i.get(r)?.includes(r))return[r,r];for(let o of i.get(r)??[]){if(!n.has(o))continue;let s=ae(i,n,r,o);if(s)return s}return[...e,e[0]]}function ae(i,e,t,n){let r=[[n]],o=new Set([t,n]);for(;r.length>0;){let s=r.shift(),c=s.at(-1);for(let a of i.get(c)??[]){if(a===t)return[t,...s,t];!e.has(a)||o.has(a)||(o.add(a),r.push([...s,a]))}}}function ve(i,e,t){let n=m(),r=H(i,n,t),o=H(e,n,t),s=new Set(r.cycles.map(K)),c=new Set(k(i,void 0,n).map(a=>`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`));return[...k(e,void 0,n).filter(a=>a.holder_id.toLowerCase()===t.trim().toLowerCase()&&!c.has(`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`)).map(a=>`ordering_storage_contradiction_created:${V(a)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...o.cycles.filter(a=>!s.has(K(a))).map(a=>`ordering_cycle_created:${se(o.successors,a,o.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function Ee(i,e){let t=e.resolve(i);return t?.hierarchy===!0||t?.outgoing==="one"||t?.incoming==="one"}function J(i,e,t,n,r){let o=JSON.stringify([e,t,n]),s=i.get(o);s===void 0&&(s={kind:e,direction:t,node_id:n,endpoints:new Set},i.set(o,s)),s.endpoints.add(r)}function B(i,e){let t=new Map;for(let n of i)for(let r of n.dependencies??[]){let o=e.resolve(r.kind);o===void 0||o.hierarchy||(o.outgoing==="one"&&J(t,o.kind,"outgoing",n.id,r.id),o.incoming==="one"&&J(t,o.kind,"incoming",r.id,n.id))}return t}function Ie(i,e,t=m()){let n=B(i,t),r=B(e,t);for(let o of[...r.keys()].sort()){let s=r.get(o);if(s.endpoints.size<=1)continue;let c=n.get(o);if(![...s.endpoints].every(a=>c?.endpoints.has(a)))throw new C(`Relationship ${s.kind} permits only one ${s.direction} endpoint for ${s.node_id}.`,S.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:s.kind,relationship_cardinality:{kind:s.kind,direction:s.direction,node_id:s.node_id,endpoint_ids:[...s.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}export{T as a,F as b,ve as c,Ee as d,Ie as e};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-DRN4W3YJ.js.map
|