@unbrained/pm-cli 2026.10.21 → 2026.10.22

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.
Files changed (138) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +117 -77
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/{chunk-KBSVPUFD.js → chunk-35ISFIPC.js} +35 -35
  6. package/dist/cli-bundle/chunks/{chunk-DIR3YEFD.js → chunk-5LSN7K4N.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-DR6DUBTU.js → chunk-7OTYULIJ.js} +3 -3
  8. package/dist/cli-bundle/chunks/{chunk-TMXWWOPJ.js → chunk-AOAQDCXX.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-ZNKFMIVA.js → chunk-BAIVTLJM.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-NNB65OOO.js → chunk-C37RDYZI.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-EMGMLKRV.js → chunk-E3JC3WQL.js} +4 -4
  12. package/dist/cli-bundle/chunks/{chunk-5PZ7JNMI.js → chunk-HC2DCGFA.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-V5GJTXYW.js → chunk-J444ZX23.js} +26 -26
  14. package/dist/cli-bundle/chunks/{chunk-V3XONSVC.js → chunk-LIC5EUQS.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-DJQVNDXO.js → chunk-MV3KYY2A.js} +6 -6
  16. package/dist/cli-bundle/chunks/chunk-O67N62DT.js +2 -0
  17. package/dist/cli-bundle/chunks/{chunk-C6SAXKBO.js → chunk-PCPOTFJP.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-TNU3XVPC.js +20 -0
  19. package/dist/cli-bundle/chunks/{chunk-MOC5BJHW.js → chunk-URV4VHQ4.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-QPV6UD55.js → chunk-UYYTV2TX.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +9 -0
  22. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-65XXSPPR.js → indexed-receipt-blobs-L3BOTMZN.js} +2 -2
  23. package/dist/cli-bundle/chunks/{mutation-admission-FNWOVJLN.js → mutation-admission-TATOFEXF.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-list-query-6PT5Y2EZ.js → register-list-query-GULR2IYO.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-mutation-TAIQV46L.js → register-mutation-HLSQ4WVW.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-operations-ONIRO22G.js → register-operations-FE3GGA7O.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-setup-OQMUZBJV.js → register-setup-XUIKAIZA.js} +2 -2
  28. package/dist/cli-bundle/chunks/{stage-FCPVFO3B.js → stage-QCPZBZRC.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/chunk-25L3L2PF.js +2 -0
  30. package/dist/cli-bundle/focused-chunks/{chunk-PDOWLRHC.js → chunk-25NQRZ7J.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-XE7P7N5X.js → chunk-2GFTVXKZ.js} +6 -6
  32. package/dist/cli-bundle/focused-chunks/chunk-46HBJC6J.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-32ZKLRWM.js → chunk-A52W6GLA.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/chunk-CB7TSZ7P.js +3 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-5IMM7GOF.js → chunk-CX5FNEFC.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +9 -0
  37. package/dist/cli-bundle/focused-chunks/{chunk-VD64TPXI.js → chunk-EHPRSWJE.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-P5D7MHDS.js → chunk-GC4VMLXL.js} +15 -15
  39. package/dist/cli-bundle/focused-chunks/{chunk-CUWNNU4N.js → chunk-GVKYTDOH.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-HNCMYF2W.js → chunk-KM77WU5U.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-QGDKWULS.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-YIWDX6KO.js → chunk-QWKCQ5PW.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-4HJVAUFX.js → chunk-SXVJRLLP.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-KVYUQS6Y.js → chunk-TMN3RAXZ.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-7UD7XTOE.js → chunk-UQ5JPBY2.js} +11 -11
  47. package/dist/cli-bundle/focused-chunks/{chunk-JMZPZQHR.js → chunk-UUPJ6OZL.js} +13 -13
  48. package/dist/cli-bundle/focused-chunks/{chunk-JI3RXXRN.js → chunk-VYAZND5Q.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-T27TLSEU.js → chunk-W2CND3BD.js} +3 -3
  50. package/dist/cli-bundle/focused-chunks/{chunk-44353U27.js → chunk-XX5JQCLF.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-CRP6HAZY.js → indexed-receipt-blobs-AAQOKO5B.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{mutation-admission-KM57KDDF.js → mutation-admission-TBKR4KRM.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{stage-UJYGWNZ7.js → stage-RM6MJIMT.js} +2 -2
  54. package/dist/cli-bundle/main.js +21 -21
  55. package/dist/cli-bundle/sdk-authoring.js +1 -1
  56. package/dist/cli-bundle/sdk-contracts.js +2 -2
  57. package/dist/cli-bundle/sdk-core.js +21 -21
  58. package/dist/cli-bundle/sdk-governance.js +1 -1
  59. package/dist/cli-bundle/sdk-graph.js +1 -1
  60. package/dist/cli-bundle/sdk-merge.js +58 -58
  61. package/dist/cli-bundle/sdk-query.js +1 -1
  62. package/dist/cli-bundle/sdk-runtime.js +1 -1
  63. package/dist/cli-bundle/sdk-testing.js +1 -1
  64. package/dist/cli-bundle/sdk.js +7 -7
  65. package/dist/mcp/server.d.ts +2 -2
  66. package/dist/mcp/server.js +1 -1
  67. package/dist/sdk/agent/command-recovery.d.ts +2 -0
  68. package/dist/sdk/agent/command-recovery.js +1 -1
  69. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
  70. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  71. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  72. package/dist/sdk/context-intent-contracts.d.ts +13 -0
  73. package/dist/sdk/context-intent-contracts.js +1 -1
  74. package/dist/sdk/contracts.d.ts +1 -1
  75. package/dist/sdk/contracts.js +1 -1
  76. package/dist/sdk/core.d.ts +2 -2
  77. package/dist/sdk/core.js +1 -1
  78. package/dist/sdk/define.d.ts +15 -16
  79. package/dist/sdk/define.js +1 -1
  80. package/dist/sdk/dependencies.js +1 -1
  81. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  82. package/dist/sdk/merge/install.js +2 -2
  83. package/dist/sdk/public-surface.json +1 -1
  84. package/dist/sdk/query/context.d.ts +5 -0
  85. package/dist/sdk/query/context.js +2 -2
  86. package/dist/sdk/read-output/session-result.d.ts +39 -0
  87. package/dist/sdk/read-output/session-result.js +2 -0
  88. package/dist/sdk/read-output-contracts.d.ts +18 -5
  89. package/dist/sdk/read-output-contracts.js +1 -1
  90. package/dist/sdk/read-output-session.d.ts +2 -0
  91. package/dist/sdk/read-output-session.js +1 -1
  92. package/dist/sdk/relationship-context.js +1 -1
  93. package/dist/sdk/runtime-input.js +1 -1
  94. package/dist/sdk/runtime-primitives.d.ts +6 -0
  95. package/dist/sdk/runtime-primitives.js +1 -1
  96. package/dist/sdk/runtime.d.ts +10 -8
  97. package/dist/sdk/runtime.js +1 -1
  98. package/dist/sdk/workspace.d.ts +3 -1
  99. package/dist/sdk/workspace.js +8 -5
  100. package/docs/CONFIGURATION.md +9 -0
  101. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +30 -0
  102. package/docs/MCP_OPTION_CONFORMANCE.md +27 -1
  103. package/docs/MERGE_SAFETY.md +8 -0
  104. package/docs/READ_OUTPUT_CONTRACTS.md +79 -0
  105. package/docs/RELATIONSHIP_GRAPH.md +15 -0
  106. package/docs/RELEASING.md +8 -0
  107. package/docs/SDK.md +37 -7
  108. package/docs/TESTING.md +5 -0
  109. package/marketplace.json +1 -1
  110. package/package.json +1 -1
  111. package/packages/pm-beads/package.json +1 -1
  112. package/packages/pm-calendar/package.json +1 -1
  113. package/packages/pm-command-kit/package.json +1 -1
  114. package/packages/pm-digital-twin/package.json +1 -1
  115. package/packages/pm-governance-audit/package.json +1 -1
  116. package/packages/pm-guide-shell/package.json +1 -1
  117. package/packages/pm-kanban/package.json +1 -1
  118. package/packages/pm-lifecycle-hooks/package.json +1 -1
  119. package/packages/pm-linked-test-adapters/package.json +1 -1
  120. package/packages/pm-search-advanced/package.json +1 -1
  121. package/packages/pm-templates/package.json +1 -1
  122. package/packages/pm-todos/package.json +1 -1
  123. package/packages/pm-vcs/package.json +1 -1
  124. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  125. package/plugins/pm-claude/package.json +1 -1
  126. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  127. package/plugins/pm-codex/package.json +1 -1
  128. package/plugins/pm-codex/plugin.json +1 -1
  129. package/runtime-dependencies.json +1 -1
  130. package/dist/cli-bundle/chunks/chunk-4OYU5OXQ.js +0 -6
  131. package/dist/cli-bundle/chunks/chunk-DIKQ2AL5.js +0 -2
  132. package/dist/cli-bundle/chunks/chunk-MZZIAC6S.js +0 -20
  133. package/dist/cli-bundle/focused-chunks/chunk-6QSZHRM7.js +0 -6
  134. package/dist/cli-bundle/focused-chunks/chunk-E2S42XCT.js +0 -2
  135. package/dist/cli-bundle/focused-chunks/chunk-GRSQGMRR.js +0 -2
  136. package/dist/cli-bundle/focused-chunks/chunk-IAGFXKMZ.js +0 -3
  137. package/dist/cli-bundle/focused-chunks/chunk-O3M6YWVL.js +0 -2
  138. package/dist/cli-bundle/focused-chunks/chunk-VE6MTRH5.js +0 -2
@@ -1,4 +1,4 @@
1
- import{c as kt,d as sn,e as cn,f as dn,g as Rl}from"./chunk-XE7P7N5X.js";import{a as Il}from"./chunk-6QSZHRM7.js";import{d as Q,h as Ba,s as vl}from"./chunk-GRSQGMRR.js";import{a as $a,c as Oi,d as Pi,e as Bc,g as Jc,h as Oa,i as Vc,j as Yt,k as Xt,l as Kc,m as Yc,n as Pa,o as Qc,p as Zt,q as Qt,r as ed,s as td,t as La}from"./chunk-HNCMYF2W.js";import{a as Ma}from"./chunk-SVOOGGAK.js";import{B as pd,C as Fi,D as fd,E as Na,G as hd,H as _d,J as gd,K as yd,L as Ui,O as Hi}from"./chunk-IAGFXKMZ.js";import{K as Al}from"./chunk-4HJVAUFX.js";import{A as xl,I as Va,w as El,y as Ja,z as Sl}from"./chunk-32ZKLRWM.js";import{E as er,Ga as _l,Ha as gl,La as yl,Ma as wl,U as ar,V as Bd,W as za,X as jn,Z as Wa,ba as rl,ca as al,da as ol,ea as sl,f as wd,fa as cr,g as vd,h as bd,ha as cl,i as kd,ia as dl,ja as ll,k as Wi,ka as Nt,la as ul,ma as an,na as ml,o as Pn,oa as qa,p as Ed,pa as on,q as Sd,qa as pl,r as Ln,ra as fl,sa as hl,ta as Ga,z as xd}from"./chunk-P5D7MHDS.js";import{a as zc,b as Kt,c as Da,d as Wc,e as qc,f as et,g as Li,h as Gc,i as gt}from"./chunk-CUWNNU4N.js";import{m as Fn,o as dr,v as bl,y as kl}from"./chunk-E2S42XCT.js";import{B as tl,C as ge,D as ye,E as nl,F as sr,G as nt,H as it,K as il,L as rt,a as zi,c as zd,j as Jd,k as Vd,m as Kd,n as Yd,o as bt,p as Xd,q as Zd,t as Qd,u as el,z as or}from"./chunk-YIWDX6KO.js";import{$a as rr,Aa as Ud,Ca as Xi,Da as Zi,Ea as Ua,Fa as vt,Ga as Mn,Ha as Hd,Ia as Qi,Ja as Lt,Ka as re,La as tr,Ma as Wd,Na as Ha,Oa as nr,Pa as rn,Qa as ir,Sa as qd,Wa as Me,Za as Gd,_a as $,a as Id,aa as W,ba as Od,ca as tt,d as Re,da as Pd,db as te,e as ja,f as Rd,ja as Ld,k as qi,ka as Fa,l as Nn,la as Vi,m as Ad,ma as tn,n as Gi,o as Cd,oa as Ki,pa as Nd,q as Bi,qa as Md,r as Ji,sa as jd,t as Td,u as De,ua as Fd,x as wt,xa as Yi,y as $d,z as Dd,za as nn}from"./chunk-JI3RXXRN.js";import{b as Bt}from"./chunk-VD64TPXI.js";import{a as oe,c as $e,e as Ie,f as Je,j as pe,k as Xc,l as Ni,n as Zc}from"./chunk-KVYUQS6Y.js";import{Ad as Pt,Ba as Cc,Bb as jc,Ca as Dt,Cb as Fc,Cc as cd,Dc as _e,Ea as Tc,Fa as C,Fd as ld,Ga as $c,Ha as xe,Hd as ud,Id as md,Ja as Di,Jd as ie,Ka as Dc,Kb as Uc,La as Ra,Lb as Ot,Ma as Aa,Na as Ca,Nb as Ta,O as Ec,Ob as Hc,Pa as Oc,Pb as Vt,Qa as Pc,R as Sc,Rb as Ge,T as Ia,Ta as Lc,Tb as Be,Wb as nd,Y as le,Yb as Mi,Z as We,Zb as id,_ as xc,_b as rd,a as hc,aa as Y,ac as ad,bb as Nc,d as _c,da as Ic,e as gc,ic as F,kb as Mc,mc as V,o as xa,oa as Rc,oc as Ne,pa as Ac,pc as od,qa as H,qc as ji,va as On,wa as M,wd as T,xa as qe,xc as sd,xd as dd,ya as $i,yd as en,za as Jt,zd as yt}from"./chunk-JMZPZQHR.js";import{a as Un}from"./chunk-VVRXF4JO.js";import{A as Dn,B as O,C as _t,D as j,E as B,H as Z,a as Ai,d as Ci,o as yc,q as wc,s as vc,u as bc,v as Ti,w as kc,y as g,z as y}from"./chunk-3LWH2RJC.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}},Ve=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 y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Ka(e){try{return await e()}catch(t){throw t instanceof we?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as ng}from"node:crypto";import ig 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 Tl=1,Mt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Ya=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],rg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],ag=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,lr=30,ur=5e3,$l=4,og=50;function at(e,t){if(!ag.test(e))throw new L(`${t} must be a stable lowercase id`)}function sg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Hn(e){let t=rg.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 Za(e,t){return C(e)===C(t)}function Dl(e,t){if(t.polarity==="equals")return Za(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 Ol(e){let t=Hn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Dl(i.observed,t)===(i.expected==="pass"))}function cg(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!Za(e.value,t.value)}function dg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||C(e.scope)!==C(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return cg(Hn(e),Hn(t))||n[t.enforcement]<n[e.enforcement]||i}function lg(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 ug(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new L("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new L("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new L("dependency_kind source source_kind_state must be present or missing")}function mg(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 Qa(e){at(e.id,"measurement.id"),e.max_cost!==void 0&&sg(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 ${Ya.join(", ")}`);let n=Reflect.get(t,"kind");if(!Ya.includes(n))throw new L(`measurement.source.kind must be one of ${Ya.join(", ")}`);let i=t;if(i.kind==="items"&&lg(i),i.kind==="dependency_kind"&&ug(i),i.kind==="prose_edge_gap"&&mg(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"&&(at(i.provider,"provider source provider"),at(i.key,"provider source key")),e}function eo(e){if(at(e.id,"assertion.id"),at(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=Hn(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"&&at(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(!Ol(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function pg(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)at(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Mt.includes(t))throw new L(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new L(`gate provider policy trigger ${t} is invalid`)}}function Pl(e){if(at(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)at(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${Mt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Mt.includes(t))throw new L(`gate trigger must be one of ${Mt.join(", ")}`);return e.provider_policy&&pg(e.provider_policy),e}function mn(e){if(e.version!==Tl)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(Qa(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(eo(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){Pl(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 Ll(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function to(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)to(n,t)}function Ll(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=[];to(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function fg(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"&&to(o.source.expression,n)}return r}function zn(){return{version:Tl,measurements:[],assertions:[],gates:[]}}function hg(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 Za(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function _g(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function gg(e,t){let n=[],i=Ia(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=Ia(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&_g(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function yg(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 wg(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 Xa(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function vg(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(Xa(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(Xa(o.id,s));for(let s of yg(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 bg(e,t){let n=vg(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=Xa(o.holder_id,d);if(n.linked_pairs.has(l)||wg(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 kg(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 Eg(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 Sg(e,t){let n=e.source;return n.kind==="items"?hg(n,t):n.kind==="dependency_kind"?gg(n,t):n.kind==="prose_edge_gap"?bg(n,t):n.kind==="history"?kg(n,t):n.kind==="links"?Eg(n,t):null}function Nl(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 xg(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 Ml(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 jl(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 Fl(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 Ml(e.operands,$l,o=>jl(o,t,n,i,r));return{value:xg(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 Ig(e,t,n,i,r){Qa(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await jl(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=Sg(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=Nl([...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:${ng("sha256").update(C(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Fl(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=Ig(e,t,n,i,r).catch(s=>{if(s instanceof Ve&&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 Ve(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function no(e,t,n=[e]){return Fl(e,t,n,[],{cache:new Map,charged:new Set})}function Rg(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 Ag(e,t,n={}){eo(e);let i=Hn(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:Rg(t.value,i),verdict:r?"retired":Dl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Ol(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Cg(e,t,n,i){let r=fg(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 Cl(e,t,n,i,r){try{return await no(n,i,r)}catch(a){if(a instanceof Ve){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 Ul(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}`);Cg(r,t,n,i.trigger);let a=await Ml(r.assertion_ids,$l,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 Cl(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 Ag(d,await Cl(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:Nl(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function mr(e){return ig.join(e,"assurance.json")}async function Hl(e){let t=await B(mr(e));return t===null?zn():pr(t)}function pr(e){try{return mn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function fr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Tg(e,t){e==="measurement"?Qa(t):e==="assertion"?eo(t):Pl(t)}async function Wn(e,t){let n=structuredClone(fr(await Hl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function zl(e,t,n){let i=fr(await Hl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function hr(e,t,n,i={}){Tg(t,n);let r=await $(e),a=W(i.author,r.author_default),o=await rn({pmRoot:e,filePath:mr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:lr,lockWaitMs:ur,mutate:s=>{let c=s===null?zn():pr(s),d=fr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&dg(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 kt,d as sn,e as cn,f as dn,g as Rl}from"./chunk-2GFTVXKZ.js";import{a as Il}from"./chunk-DVNUHTVK.js";import{d as Q,h as Ba,s as vl}from"./chunk-25L3L2PF.js";import{a as $a,c as Oi,d as Pi,e as Bc,g as Jc,h as Oa,i as Vc,j as Yt,k as Xt,l as Kc,m as Yc,n as Pa,o as Qc,p as Zt,q as Qt,r as ed,s as td,t as La}from"./chunk-KM77WU5U.js";import{a as Ma}from"./chunk-SVOOGGAK.js";import{B as pd,C as Fi,D as fd,E as Na,G as hd,H as _d,J as gd,K as yd,L as Ui,U as Hi}from"./chunk-CB7TSZ7P.js";import{K as Al}from"./chunk-SXVJRLLP.js";import{A as xl,I as Va,w as El,y as Ja,z as Sl}from"./chunk-A52W6GLA.js";import{E as er,Ga as _l,Ha as gl,La as yl,Ma as wl,U as ar,V as Bd,W as za,X as jn,Z as Wa,ba as rl,ca as al,da as ol,ea as sl,f as wd,fa as cr,g as vd,h as bd,ha as cl,i as kd,ia as dl,ja as ll,k as Wi,ka as Nt,la as ul,ma as an,na as ml,o as Pn,oa as qa,p as Ed,pa as on,q as Sd,qa as pl,r as Ln,ra as fl,sa as hl,ta as Ga,z as xd}from"./chunk-GC4VMLXL.js";import{a as zc,b as Kt,c as Da,d as Wc,e as qc,f as et,g as Li,h as Gc,i as gt}from"./chunk-GVKYTDOH.js";import{m as Fn,o as dr,v as bl,y as kl}from"./chunk-QGDKWULS.js";import{B as tl,C as ge,D as ye,E as nl,F as sr,G as nt,H as it,K as il,L as rt,a as zi,c as zd,j as Jd,k as Vd,m as Kd,n as Yd,o as bt,p as Xd,q as Zd,t as Qd,u as el,z as or}from"./chunk-QWKCQ5PW.js";import{$a as rr,Aa as Ud,Ca as Xi,Da as Zi,Ea as Ua,Fa as vt,Ga as Mn,Ha as Hd,Ia as Qi,Ja as Lt,Ka as re,La as tr,Ma as Wd,Na as Ha,Oa as nr,Pa as rn,Qa as ir,Sa as qd,Wa as Me,Za as Gd,_a as $,a as Id,aa as W,ba as Od,ca as tt,d as Re,da as Pd,db as te,e as ja,f as Rd,ja as Ld,k as qi,ka as Fa,l as Nn,la as Vi,m as Ad,ma as tn,n as Gi,o as Cd,oa as Ki,pa as Nd,q as Bi,qa as Md,r as Ji,sa as jd,t as Td,u as De,ua as Fd,x as wt,xa as Yi,y as $d,z as Dd,za as nn}from"./chunk-VYAZND5Q.js";import{b as Bt}from"./chunk-EHPRSWJE.js";import{a as oe,c as $e,e as Ie,f as Je,j as pe,k as Xc,l as Ni,n as Zc}from"./chunk-TMN3RAXZ.js";import{Ad as Pt,Ba as Cc,Bb as jc,Ca as Dt,Cb as Fc,Cc as cd,Dc as _e,Ea as Tc,Fa as C,Fd as ld,Ga as $c,Ha as xe,Hd as ud,Id as md,Ja as Di,Jd as ie,Ka as Dc,Kb as Uc,La as Ra,Lb as Ot,Ma as Aa,Na as Ca,Nb as Ta,O as Ec,Ob as Hc,Pa as Oc,Pb as Vt,Qa as Pc,R as Sc,Rb as Ge,T as Ia,Ta as Lc,Tb as Be,Wb as nd,Y as le,Yb as Mi,Z as We,Zb as id,_ as xc,_b as rd,a as hc,aa as Y,ac as ad,bb as Nc,d as _c,da as Ic,e as gc,ic as F,kb as Mc,mc as V,o as xa,oa as Rc,oc as Ne,pa as Ac,pc as od,qa as H,qc as ji,va as On,wa as M,wd as T,xa as qe,xc as sd,xd as dd,ya as $i,yd as en,za as Jt,zd as yt}from"./chunk-UUPJ6OZL.js";import{a as Un}from"./chunk-VVRXF4JO.js";import{A as Dn,B as O,C as _t,D as j,E as B,H as Z,a as Ai,d as Ci,o as yc,q as wc,s as vc,u as bc,v as Ti,w as kc,y as g,z as y}from"./chunk-3LWH2RJC.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}},Ve=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 y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Ka(e){try{return await e()}catch(t){throw t instanceof we?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as ng}from"node:crypto";import ig 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 Tl=1,Mt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Ya=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],rg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],ag=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,lr=30,ur=5e3,$l=4,og=50;function at(e,t){if(!ag.test(e))throw new L(`${t} must be a stable lowercase id`)}function sg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Hn(e){let t=rg.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 Za(e,t){return C(e)===C(t)}function Dl(e,t){if(t.polarity==="equals")return Za(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 Ol(e){let t=Hn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Dl(i.observed,t)===(i.expected==="pass"))}function cg(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!Za(e.value,t.value)}function dg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||C(e.scope)!==C(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return cg(Hn(e),Hn(t))||n[t.enforcement]<n[e.enforcement]||i}function lg(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 ug(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new L("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new L("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new L("dependency_kind source source_kind_state must be present or missing")}function mg(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 Qa(e){at(e.id,"measurement.id"),e.max_cost!==void 0&&sg(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 ${Ya.join(", ")}`);let n=Reflect.get(t,"kind");if(!Ya.includes(n))throw new L(`measurement.source.kind must be one of ${Ya.join(", ")}`);let i=t;if(i.kind==="items"&&lg(i),i.kind==="dependency_kind"&&ug(i),i.kind==="prose_edge_gap"&&mg(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"&&(at(i.provider,"provider source provider"),at(i.key,"provider source key")),e}function eo(e){if(at(e.id,"assertion.id"),at(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=Hn(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"&&at(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(!Ol(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function pg(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)at(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Mt.includes(t))throw new L(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new L(`gate provider policy trigger ${t} is invalid`)}}function Pl(e){if(at(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)at(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${Mt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!Mt.includes(t))throw new L(`gate trigger must be one of ${Mt.join(", ")}`);return e.provider_policy&&pg(e.provider_policy),e}function mn(e){if(e.version!==Tl)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(Qa(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(eo(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){Pl(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 Ll(e))if(!n.has(i))throw new L(`${r.join(", ")} references missing measurement ${i}`);return e}function to(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)to(n,t)}function Ll(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=[];to(i.source.expression,r);for(let a of r)n(a,`derived measurement ${i.id}`)}return t}function fg(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"&&to(o.source.expression,n)}return r}function zn(){return{version:Tl,measurements:[],assertions:[],gates:[]}}function hg(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 Za(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function _g(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function gg(e,t){let n=[],i=Ia(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=Ia(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&_g(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function yg(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 wg(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 Xa(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function vg(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(Xa(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(Xa(o.id,s));for(let s of yg(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 bg(e,t){let n=vg(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=Xa(o.holder_id,d);if(n.linked_pairs.has(l)||wg(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 kg(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 Eg(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 Sg(e,t){let n=e.source;return n.kind==="items"?hg(n,t):n.kind==="dependency_kind"?gg(n,t):n.kind==="prose_edge_gap"?bg(n,t):n.kind==="history"?kg(n,t):n.kind==="links"?Eg(n,t):null}function Nl(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 xg(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 Ml(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 jl(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 Fl(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 Ml(e.operands,$l,o=>jl(o,t,n,i,r));return{value:xg(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 Ig(e,t,n,i,r){Qa(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await jl(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=Sg(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=Nl([...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:${ng("sha256").update(C(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Fl(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=Ig(e,t,n,i,r).catch(s=>{if(s instanceof Ve&&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 Ve(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function no(e,t,n=[e]){return Fl(e,t,n,[],{cache:new Map,charged:new Set})}function Rg(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 Ag(e,t,n={}){eo(e);let i=Hn(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:Rg(t.value,i),verdict:r?"retired":Dl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Ol(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function Cg(e,t,n,i){let r=fg(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 Cl(e,t,n,i,r){try{return await no(n,i,r)}catch(a){if(a instanceof Ve){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 Ul(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}`);Cg(r,t,n,i.trigger);let a=await Ml(r.assertion_ids,$l,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 Cl(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 Ag(d,await Cl(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:Nl(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function mr(e){return ig.join(e,"assurance.json")}async function Hl(e){let t=await B(mr(e));return t===null?zn():pr(t)}function pr(e){try{return mn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function fr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Tg(e,t){e==="measurement"?Qa(t):e==="assertion"?eo(t):Pl(t)}async function Wn(e,t){let n=structuredClone(fr(await Hl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function zl(e,t,n){let i=fr(await Hl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function hr(e,t,n,i={}){Tg(t,n);let r=await $(e),a=W(i.author,r.author_default),o=await rn({pmRoot:e,filePath:mr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:lr,lockWaitMs:ur,mutate:s=>{let c=s===null?zn():pr(s),d=fr(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&dg(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 io(e,t,n={}){let i=zn();i.measurements=structuredClone(t.measurements),i.assertions=structuredClone(t.assertions),i.gates=structuredClone(t.gates),mn(i);let r=await $(e),a=W(n.author,r.author_default),o=await rn({pmRoot:e,filePath:mr(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:lr,lockWaitMs:ur,mutate:s=>{let c=s===null?zn():pr(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let _=m.find(w=>w.id===h.id);if(!_){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(C(_)!==C(h))throw new L(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,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 Wl(e,t,n,i={}){let r=await $(e),a=W(i.author,r.author_default),o=await rn({pmRoot:e,filePath:mr(e),op:`assurance:${t}:remove`,author:a,message:i.message,lockTtlSeconds:lr,lockWaitMs:ur,mutate:s=>{let c=s===null?zn():pr(s);if(t==="measurement"){let u=Ll(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=fr(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 ql(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await $(e);await nr({pmRoot:e,op:"assurance:gate:verdict",author:W(n.author,i.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:lr,lockWaitMs:ur})}async function Gl(e,t={}){let n=t.limit??og;if(!Number.isInteger(n)||n<1||n>un)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${un}`);return(await tt(tr(e),re)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var qn={type:"string",minLength:1,maxLength:128,pattern:"\\S"},_r={type:"array",minItems:1,maxItems:Ra,items:qn},Bl={..._r,items:{...qn,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},$g={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,_r])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:qn,id:qn}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Bl}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:_r}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Bl,authors:_r}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:Ra,items:{type:"array",minItems:2,maxItems:2,items:qn}}}}]}}},AC={$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:Dc,items:$g}}};(function(){try{var e=typeof window<"u"?window:typeof 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 Jl(e,t,n,i){let r=await bt(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"]}:Vl(r,t,n,i)}function Dg(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Vl(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=Lc(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:Dg(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 Og from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function Pg(){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 Xl(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new y("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Policy definition must be an object.",g.USAGE);return t}async function Lg(e,t){let n=M(process.cwd(),e.path);await te(n);let i=await $(n);return{pmRoot:n,settings:i,author:W(t,i.author_default)}}function Kl(e,t,n,i){if(e==="policy-mode")return Ca({...n,enforcement:t});let r=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:r};let a=Aa(i.definition),o=Ca({...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}`,g.GENERIC_FAILURE)}}function Mm(e){let t=e.trim(),n=t.includes("@file:")?t
49
49
  `,conflict_paths:c,paths_from_theirs:d,preferred:r}}import Br from"node:path";import{execFile as cS}from"node:child_process";import{createHash as gf}from"node:crypto";import{readdir as dS}from"node:fs/promises";import lS from"node:path";import{promisify as uS}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 lt=uS(cS),Gr=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function $N(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 lt("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Un(o.trim(),128))?.trim();if(s===void 0||!Gr.test(s))continue;let{stdout:c}=await lt("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 lt("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!Gr.test(o))return;let{stdout:c}=await lt("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),d=c.trim(),l=gf(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 yf(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"&&Gr.test(t.original_head)&&typeof t.original_blob=="string"&&Gr.test(t.original_blob)}async function wf(e,t,n,i){if(i!==void 0&&gf(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 lt("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 dS(r.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await lt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await lt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await lt("git",["hash-object","--",lS.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await lt("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 mS=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,pS=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Vr=2048,fS=64,hS=1e5,_S=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 ut(e){return mS.test(e)}var gS=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),Kr="bounded_non_sensitive_scalars_v1",yS=new Set(["open","in_progress","blocked","closed","canceled"]),wS=new Set(["risk","confidence","severity"]),vS=new Set(["low","medium","high","critical"]),bf=new Map([["priority",new Set([0,1,2,3,4].map(C))],["status",new Set([...yS].map(C))],...[...wS].map(e=>[e,new Set([...vS].map(C))])]);function Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kf(e,t){return Object.keys(e).every(n=>t.has(n))}function Jr(e){return Array.isArray(e)&&e.length<=Vr&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function pi(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let i=t.pop();if(n+=1,n>hS||i.depth>fS)return!1;if(Array.isArray(i.value))for(let r of i.value)t.push({value:r,depth:i.depth+1});else if(Ze(i.value))for(let r of Object.values(i.value))t.push({value:r,depth:i.depth+1})}return!0}function Ef(e){if(!Ze(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[kf(e,gS),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"),pi(e.base),pi(e.ours),pi(e.theirs),pi(e.retained),pi(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function bS(e){if(!Ze(e))return!1;let t=Object.entries(e);return t.length<=Vr&&t.every(([n,i])=>n.length>0&&n.length<=256&&typeof i=="string"&&/^[a-f0-9]{64}$/u.test(i))}function kS(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||Br.posix.isAbsolute(e))return!1;let n=Br.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&Br.posix.basename(n,Br.posix.extname(n))===t}function ES(e){return!Jr(e.fields_from_theirs)||!Jr(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Vr||!e.decisions.every(Ef)?!1:e.merged_field_hashes===void 0||bS(e.merged_field_hashes)}function SS(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===Kr)&&r.includes(e.evidence_source)}function xS(e){return typeof e.created_at=="string"&&en(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&en(e.reconciled_at))}function vf(e,t){if(!Ze(t)||Zr(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||bf.get(e)?.has(C(i))===!0)&&At(i)===t.pm_value_hash}function IS(e){if(!e.decisions.every(i=>i.base===null&&i.ours===null&&i.theirs===null&&vf(i.field,i.retained)&&vf(i.field,i.discarded)))return!1;let t=e.decisions.reduce((i,r)=>i+(Ze(r.retained)&&Object.hasOwn(r.retained,"pm_value")?1:0)+(Ze(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===Kr)}function RS(e){return e.operation!==void 0&&!yf(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function AS(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||!kf(e,_S)?"required_fields":typeof e.id!="string"||!ut(e.id)?"receipt_id":typeof e.item_id!="string"||!pS.test(e.item_id)?"item_id":kS(e.item_path,e.item_id)?null:"item_path"}function Yr(e,t){if(!Ze(e))return"required_fields";let n=AS(e);return n!==null?n:RS(e)?ES(e)?SS(e)?xS(e)?t==="durable"&&!IS(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function Xr(e){if(!Ze(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=>!Ze(i)||!Object.hasOwn(i,"retained")||!Object.hasOwn(i,"discarded")?i:{base:J(void 0),ours:J(void 0),theirs:J(void 0),...i})}}function Sf(e){if(!Ze(e))return;if(!Jr(e.fields_from_theirs))return"fields_from_theirs";if(!Jr(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>Vr)return"decisions";let t=e.decisions.findIndex(n=>!Ef(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function ds(e,t){return Yr(e,t)===null}function Zr(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 ls(e,t){let n=bn(t),i=At(n?void 0:t);return!n&&(t===null||bf.get(e)?.has(C(t))===!0)?{pm_value_hash:i,pm_value:t}:{pm_value_hash:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="21c15a9e-da38-5fec-9a7d-57556f77ce0a")}catch{}})();var PS=OS(CS),us=16*1024*1024,Qr=100;async function ms(e){try{let{stdout:t}=await PS("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 Rf(e,t){let n=ue.dirname(ue.resolve(e,t));for(let i=0;i<12;i+=1){if(await O(ue.join(n,"settings.json")))return n;let r=ue.dirname(n);if(r===n)break;n=r}return null}function ea(e){return ue.join(e,"merge-receipts")}function Ct(e){return`${e}.json`}async function xf(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Un(e.receiptPath,us)}catch(a){if(_t(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=Xr(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!ds(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ue.basename(e.receiptPath)!==Ct(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:i,...r}=n;return{path:e.receiptPath,fingerprints:hi(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 fi(e,t=!1){return xe(C({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:xe(C(J(n.retained))),discarded_hash:xe(C(J(n.discarded)))})):ta(e).decisions}))}function hi(e){let t=[fi(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(fi(e,!0)),t}function LS(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 NS(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 tt(ue.join(n,"history",`${a.item_id}.jsonl`),a.item_id),vt(o).ok||(o=[])}catch{o=[]}i.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=C({...ta(a),...s?{reason:a.settlement,operation:a.operation}:{}});if(!o.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[s?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(m=>C(m)===c)})){let{reconciled_at:d,settlement:l,...u}=a;e.set(a.id,{...u,state:"pending"})}}}function ta(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:Zr(t.retained)??At(bn(t.retained)?void 0:t.retained),discarded_hash:Zr(t.discarded)??At(bn(t.discarded)?void 0:t.discarded)}))}}async function tM(e){let t=await ms(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,r=ue.basename(i,ue.extname(i)),a={version:1,id:TS(),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:J(s.base),ours:J(s.ours),theirs:J(s.theirs),retained:J(s.retained),discarded:J(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:T(),value_availability:"clone_local"};await Dn(t),await Z(ue.join(t,Ct(a.id)),`${JSON.stringify(a,null,2)}
51
51
  `);let o=await Rf(e.cwd,a.item_path);if(o!==null){let s=ea(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:ls(u.field,u.retained),discarded:ls(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:Kr};await Dn(s),await Z(ue.join(s,Ct(a.id)),`${JSON.stringify(l,null,2)}
52
- `)}return a}async function If(e,t){let n;try{n=await $S(e)}catch(s){let c=await MS(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>=Qr)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},...ut(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 jS(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 MS(e,t,n=DS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ue.dirname(i);if(a===i)return!0;i=a}}async function jS(e,t,n){let i;try{i=await Un(ue.join(e,t),us)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=Xr(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=Yr(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:Sf(r)}:{}};let o=r;if(t!==Ct(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function FS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-CRP6HAZY.js"),r=await i(e,ea(t),n.map(a=>Ct(a.id)),us);return n.flatMap(a=>{try{let o=Xr(JSON.parse(r.get(Ct(a.id))??""));if(Yr(o,"durable")!==null)return[];let s=o,c=hi(a);return s.id===a.id&&hi(s).some(d=>c.includes(d))?[a.id]:[]}catch{return[]}})}async function mt(e,t={}){let n=await ms(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await If(n,"clone_local"),r=t.pmRoot??ue.join(e,".agents","pm"),a=await If(ea(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?hi(u):[fi(u)]).includes(fi(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<Qr&&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:LS(u,m))}await NS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await FS(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,Qr),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>Qr,clone_local_evidence_resolved:n!==null}}function Af(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 y(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,g.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function kn(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 nM(e,t,n={}){let i=await ms(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(!ds(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=T(),o=ue.join(i,Ct(t.id)),s=await Rf(e,t.item_path),c=s===null?null:ue.join(ea(s),Ct(t.id)),d=(await Promise.all([xf({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[xf({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)?[fi(t)]:hi(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 iM(e){let t=await mt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:T()}}import{createHash as US}from"node:crypto";import na 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 HS="2026-08-09T16:15:18.000Z",Tf=Symbol("pre-durable-disposition-eligible");function pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ps(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 Cf(e){return pt(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 $f(e,t){if(typeof e!="string")return!1;let n=na.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!na.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(na.posix.basename(n)===`${t}.toon`||na.posix.basename(n)===`${t}.md`)}function zS(e,t){return typeof e.receipt_id=="string"&&ut(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&$f(e.item_path,t)}function Df(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=>Cf(o)?[o.field]:[])):new Set;return ps(t)&&ps(n)&&ps(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Cf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function WS(e,t){return zS(e,t)&&Df(e)}function qS(e,t){return typeof e.receipt_id=="string"&&ut(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&&$f(e.item_path,t)&&Df(e)}function GS(e){return e[Tf]===!0}function Of(e,t){if(!pt(e)||!pt(e.context))return[];let n=e.context.merge;return!pt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!pt(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:WS(i,t),[Tf]:qS(i,t),...typeof e.ts=="string"&&en(e.ts)?{eventTimestamp:e.ts}:{}}])}function Pf(e,t,n){if(!pt(e)||e.op!=="merge_reconcile")return[];if(!pt(e.context)||!pt(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!pt(r)||typeof r.receipt_id!="string"||!ut(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"||!en(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 Lf(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=>GS(a)&&a.eventTimestamp!==void 0&&Pt(a.eventTimestamp,HS)<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,...ut(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:US("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as BS}from"node:buffer";import{readFile as JS}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 VS(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new y("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new y("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function KS(e){if(De(e))throw new y("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,i,r=0;for(let[o,s]of e.split(`
52
+ `)}return a}async function If(e,t){let n;try{n=await $S(e)}catch(s){let c=await MS(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>=Qr)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},...ut(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 jS(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 MS(e,t,n=DS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ue.dirname(i);if(a===i)return!0;i=a}}async function jS(e,t,n){let i;try{i=await Un(ue.join(e,t),us)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=Xr(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=Yr(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:Sf(r)}:{}};let o=r;if(t!==Ct(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function FS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-AAQOKO5B.js"),r=await i(e,ea(t),n.map(a=>Ct(a.id)),us);return n.flatMap(a=>{try{let o=Xr(JSON.parse(r.get(Ct(a.id))??""));if(Yr(o,"durable")!==null)return[];let s=o,c=hi(a);return s.id===a.id&&hi(s).some(d=>c.includes(d))?[a.id]:[]}catch{return[]}})}async function mt(e,t={}){let n=await ms(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await If(n,"clone_local"),r=t.pmRoot??ue.join(e,".agents","pm"),a=await If(ea(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?hi(u):[fi(u)]).includes(fi(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<Qr&&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:LS(u,m))}await NS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await FS(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,Qr),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>Qr,clone_local_evidence_resolved:n!==null}}function Af(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 y(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,g.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function kn(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 nM(e,t,n={}){let i=await ms(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(!ds(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=T(),o=ue.join(i,Ct(t.id)),s=await Rf(e,t.item_path),c=s===null?null:ue.join(ea(s),Ct(t.id)),d=(await Promise.all([xf({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[xf({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)?[fi(t)]:hi(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 iM(e){let t=await mt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:T()}}import{createHash as US}from"node:crypto";import na 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 HS="2026-08-09T16:15:18.000Z",Tf=Symbol("pre-durable-disposition-eligible");function pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ps(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 Cf(e){return pt(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 $f(e,t){if(typeof e!="string")return!1;let n=na.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!na.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(na.posix.basename(n)===`${t}.toon`||na.posix.basename(n)===`${t}.md`)}function zS(e,t){return typeof e.receipt_id=="string"&&ut(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&$f(e.item_path,t)}function Df(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=>Cf(o)?[o.field]:[])):new Set;return ps(t)&&ps(n)&&ps(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Cf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function WS(e,t){return zS(e,t)&&Df(e)}function qS(e,t){return typeof e.receipt_id=="string"&&ut(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&&$f(e.item_path,t)&&Df(e)}function GS(e){return e[Tf]===!0}function Of(e,t){if(!pt(e)||!pt(e.context))return[];let n=e.context.merge;return!pt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!pt(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:WS(i,t),[Tf]:qS(i,t),...typeof e.ts=="string"&&en(e.ts)?{eventTimestamp:e.ts}:{}}])}function Pf(e,t,n){if(!pt(e)||e.op!=="merge_reconcile")return[];if(!pt(e.context)||!pt(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!pt(r)||typeof r.receipt_id!="string"||!ut(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"||!en(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 Lf(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=>GS(a)&&a.eventTimestamp!==void 0&&Pt(a.eventTimestamp,HS)<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,...ut(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:US("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as BS}from"node:buffer";import{readFile as JS}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 VS(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new y("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new y("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function KS(e){if(De(e))throw new y("Resolve history merge conflicts before salvage.",g.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=VS(s);if(c===null){i===void 0&&(i=n,r=o+1),n+=s.length+1;continue}if(i!==void 0)throw new y("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=s.length+1}let a=vt(t);if(!a.ok||a.item_hash_version===void 0)throw new y("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:a.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:a.item_hash_version,prefix: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 YS(e,t,n){if(!e.located)return{itemRaw:null,document:n};let i=await nl(e.located,{schema:t.schema});return{itemRaw:i.raw,document:i.document??n}}async function Nf(e){let t;try{t=await JS(e)}catch(n){if(j(n))return null;throw n}if(!BS(t))throw new y("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function Mf(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 y("Tail salvage cannot be combined with other repair modes.",g.USAGE);let a=await Nf(t.historyPath);if(a===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await Ne({path:t.historyPath,scope:"project"});let o=KS(a),s=Vd(o.entries,o.entries.length-1),c=Ud(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new y("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let d=await YS(t,n,c),l=co({itemDocument:d.document,subjectId:t.id,author:r,force:i.force,settings:n}),u=o.itemHashVersion,m=i.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await ie(e.pmRoot,t.id,n.locks.ttl_seconds,r,!!i.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Nf(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 y("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=Ki({...Fd({hashAlgorithm:Re(o.entries.at(-1).hash_algorithm),nowIso:T(),author:r,op:"history_salvage",before:c,after:c,message:i.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await wr({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
54
54
  `}),l.push(...await V({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:T()}}import{realpath as zf}from"node:fs/promises";import fs from"node:path";import Wf 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 jf(e,t){return t==="body"?e.body:e.metadata[t]}function XS(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 ZS(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 Ff(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(i=>XS(e,i)))return t;let n=t.map(i=>e==="comments"?i:ZS(i));return[...new Map(n.map(i=>[C(i),i])).values()]}function hs(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)&&hs(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)&&hs(r,n[i]))}function Uf(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 Zi(a.patch))o.add(er(c.path)),c.from&&o.add(er(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 QS(e,t,n){let i=Wf.compare(t,n);if(i.length===0)return;let r=new Set;for(let p of i)r.add(er(p.path));let a=new Set([...r].filter(p=>hs(Ff(p,jf(t,p)),Ff(p,jf(n,p))))),o=new Set([...r].filter(p=>!a.has(p))),s=Uf(e,o),c=Uf(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 e0(e){try{return await zf(e)}catch{return null}}async function t0(e){if(await e0(fs.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(C(J(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function n0(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 zf(e.itemPath),i=[];for(let o of t){let s=await t0({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 Hf(e,t,n,i){if(e===void 0)return;let{receipt:r,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:fs.relative(a,t.currentItemPath).split(fs.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 wf(a,r.item_path,r.operation,t.currentItemRawBeforeLock))throw new y("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function i0(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 mt(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))??[];Af(t,n,e.options.dryRun===!0);let r=e.options.mergeReceiptProof?await n0({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 y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let a=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(ta)}}:e.options.auditContext}}function r0(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=Xi(r.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:nn(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:r.raw,loadedItem:r}}function a0(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 o0(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=nn(e.finalReplay,e.itemHashVersion,i),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(a),s=nn(n,e.itemHashVersion,i),c={hash_algorithm:i,ts:T(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Wf.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(Ki({...c,event_class:Pd(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function s0(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 _s(e,t,n){let{pmRoot:i,settings:r,typeRegistry:a}=await Ja(n.path),o=await Sl(i,e,r,a.type_to_folder);return t.salvageTail===!0?Mf({pmRoot:i,subject:o,settings:r,typeRegistry:a,options:t,author:W(t.author,r.author_default)}):Su({pmRoot:i,subject:o,settings:r,typeRegistry:a,operation:"history-repair",options:t,transform:s=>d0({pmRoot:i,subject:o,options:t},s)})}function c0(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"&&C(r.context)===C(n));return e.forceAuditEntry===!0&&!i}async function d0(e,t){let{pmRoot:n,subject:i,options:r}=e,a=t.entries,o=t.verification,s=vt(a),c=r.normalizeProvenance?yu(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=Hd(c.entries),l=new Set(c.entries.map(I=>I.item_hash_version).filter(I=>I!==void 0)),u=Qi(c.entries,d),m=r0(i,t,d);await Hf(r.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=nn(f,d),h=!1;if(m.currentItemReplay!==null){let I=nn(m.currentItemReplay,d);h=!p.some((A,K)=>A===I[K])}let _=h&&m.currentItemReplay?QS(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await i0({options:r,pmRoot:n,subjectId:i.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,c0(r,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,x=!!r.dryRun,D=a0({message:r.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=o0({reanchorEntries:u.entries,changed:E,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:D,auditOperation:r.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),P=s0(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>Hf(r.mergeAbandonmentProof,m,o.ok,u),report:({verification:I,warnings:A})=>({id:i.id,dry_run:x,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:I.ok,verify_errors:I.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([...P,...A])].sort((K,Se)=>K.localeCompare(Se)),generated_at:T()})}}function YM(e,t){if(t&&e!==void 0)throw new y("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new y("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function XM(e,t){if(e.salvageTail===!0)throw new y("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:i,typeRegistry:r}=await Ja(t.path),a=[],o=await it(n,i.item_format,r.type_to_folder,a,i.schema,{forceSourceScan:!0}),s=await Ft(n,o),c=e.normalizeProvenance?await wu(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 _s(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 Ld(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_at:T()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="29e94aff-b6c9-588b-afcb-b571bdb5804e")}catch{}})();var l0=new Set(hl),qf=25,u0=be.join("runtime","telemetry","events.jsonl"),m0=be.join("runtime","telemetry","state.json"),p0=2500,f0=500,Gf=wl-3,h0=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function ks(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Es(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function En(e){return e.trim().toLowerCase()}function ws(e,t){let n=En(e),i=En(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Ss(e){try{return(await ft.stat(e)).isDirectory()}catch{return!1}}async function _0(e){let t=(await ft.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>ft.readdir(be.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>On.some(a=>r.name.endsWith(a))).map(r=>be.parse(r.name).name)))}async function g0(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 ft.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 y0(e,t,n){let i=be.join(e,"history");if(!await Ss(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ft.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 g0(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 vs(e,t){return be.relative(e,t).replaceAll("\\","/")}async function Bf(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 ft.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&j(s))continue;continue}for(let s of o)On.some(c=>s.toLowerCase().endsWith(c))&&i.push(be.join(a,s))}return i.sort((r,a)=>vs(e,r).localeCompare(vs(e,a))),i}function w0(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function v0(e,t,n){let i=await Bf(e,t),r=[],a=[],o=[],s=[],c=Bt(F());for(let d of i){let l=vs(e,d),u;try{u=await ft.readFile(d,"utf8")}catch{r.push(l);continue}let m=De(u);if(m){a.push({path:l,...m});continue}try{let f=wt(u,{format:Cc(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:Gi(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function b0(e){let t=be.join(e,"history"),n=[],i=[],r=[],a=[],o=[],s=[];try{s=(await ft.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){w0(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await ft.readFile(be.join(t,c),"utf8")}catch{n.push(d);continue}let u=De(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(...Of(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Pf(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 Jf(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 k0(e,t,n,i,r,a){let o=await v0(e,t,n),s=await b0(e),c=Bi(o.formatVersions,Nn,qi),d=pe(n),l=dr(a,I=>Td(I,d),Fn()),u=await Wr(e),m=await kt(e),f=await of(e,m,i,r),p=m===null?null:await dn(m),h=await mt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),_=new Set(h.durable_receipt_ids),w=Lf(s.mergeReceiptReferences,_,s.mergeReceiptDispositions),v=w.missing,E=h.receipts.filter(I=>I.state==="pending"),{pendingDecisions:k,lossless:x}=kn(E),D=p?.status==="missing"&&p.missing_keys.length===5&&p.drifted_keys.length===0,S=[...o.unreadable.map(I=>`integrity_item_unreadable:${I}`),...o.conflictMarkers.map(I=>`integrity_item_conflict_marker:${I.path}:L${I.line}`),...o.parseFailures.map(I=>`integrity_item_parse_failed:${I}`),...s.unreadable.map(I=>`integrity_history_unreadable:${I}`),...s.conflictMarkers.map(I=>`integrity_history_conflict_marker:${I.id}:L${I.line}`),...s.invalidJson.map(I=>`integrity_history_invalid_json:${I.id}:L${I.line}`),...c.outdated.map(I=>`integrity_item_outdated_format_version:${I}`),...c.ahead.map(I=>`integrity_item_ahead_format_version:${I}`),...Jf(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...p!==null&&p.status!=="ok"?[`merge_driver_configuration_${D?"missing":"drift"}:${p.missing_keys.length+p.drifted_keys.length}`]:[],...f.warnings,...k.length>0?[`merge_decisions_unreviewed:${k.length}`]:[],...x.length>0?[`merge_receipts_pending:${x.length}`]:[],...sf({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:v.length})],b=[...new Set(S)].sort((I,A)=>I.localeCompare(A)),P=b.filter(I=>!I.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:p===null||p.status==="ok"?0:p.missing_keys.length+p.drifted_keys.length,merge_fence:f.count,pending_merge_decisions:k.length,lossless_merge_receipts:x.length,invalid_merge_receipt_evidence:h.invalid_evidence_count,missing_merge_receipt_history_references:v.length,accepted_legacy_merge_receipt_references:w.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:w.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:je(l.relations,Iu)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:p===null?null:{...p,required:r},merge_fence:f.audit,pending_merge_decision_items:[...new Set(k.map(I=>I.item_id))].sort((I,A)=>I.localeCompare(A)),lossless_merge_receipt_items:[...new Set(x.map(I=>I.item_id))].sort((I,A)=>I.localeCompare(A)),invalid_merge_receipt_evidence_details:h.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:h.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:v.slice(0,lo),missing_merge_receipt_history_reference_details_truncated:v.length>lo}},warnings:b,gitWorkspaceRoot:m,pendingMergeReceipts:E}}function E0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function S0(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:E0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function x0(e,t){return Y(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function I0(e){let t=Y(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function R0(e){return Y(e.reason)??Y(e.error)??Y(e.message)}function gs(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 A0(e){let t=[],n=[],i=[];e.forEach((a,o)=>{let s=x0(a.definition,o),c=I0(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:R0(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(gs),n.sort(gs),i.sort(gs);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 Vf(e,t,n,i,r,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>Es(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=Wo(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: ${Ai.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 C0(e,t,n){let i=await Yo(qe(e)),r=await Ge({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(S=>S0(S)),o=await _u(r.loaded,qe(e)),s=await Be({...r,loaded:r.loaded}),[c,d]=await Promise.all([fe(r.roots.project),fe(r.roots.global)]);await Ko(e,s.registrations.migrations);let l=A0(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=>En(S.name))),f=new Set(d.state.entries.map(S=>En(S.name))),p=[...new Map(r.loaded.filter(S=>!(S.layer==="project"?m:f).has(En(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let P=`${S.layer}:${S.name}`,I=`${b.layer}:${b.name}`;return P.localeCompare(I)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),_=p.filter(S=>ws(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!ws(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=ci(E),x=di(),D=Vf(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:D,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:k,host_version_census:o}},warnings:E}}function bs(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Ru(e,qf);return{values:n.values,truncated:n.truncated,total:e.length}}function ia(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function T0(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return l0.has(e)?e:null}function ra(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 Kf(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>=Gf&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:a}}function $0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function D0(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 O0(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Ga().telemetry_disabled?void 0:{attempted:!0,...await Yf(n)}}function P0(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>=f0;return(o||s||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function L0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function N0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>yl?[`telemetry_schema_version_behind:${t}`]:[]}function M0(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 j0(){return{...Ga(),pm_no_telemetry:ia("PM_NO_TELEMETRY"),telemetry_otel_disabled:ia("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ia("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:T0()}}function F0(e,t){return e.telemetry.enabled&&t.validEntries>0}function U0(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Yf(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(p0)});return{probe_url:ra(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of h0){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:ra(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function H0(e,t){let n=$i(process.cwd()),i=be.join(n,u0),r=be.join(n,m0),a=await B(i),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?Kf(a):$0(),d=await B(r),{runtimeState:l,stateParseFailed:u}=D0(d),m=e.telemetry.endpoint.trim(),f=ra(m),p=await O0(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...P0(e,c,l),...L0(p),...N0(p),...M0(e,l));let _=F0(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:U0(_,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:Gf,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:j0()}},warnings:h}}async function z0(e){let t;try{t=await Ku(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 W0(e){let t="metadata",n=e.items,i=await Ft(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(r.length>0){n=await it(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Ft(e.pmRoot,n),a=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,E)=>v.localeCompare(E));let w=new Set(a);o=r.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=i,_=[...s.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:r.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function q0(e,t){let n=ar(e),i=jn(n.settings),r=cr(n.settings,t),a=i.active?Nt(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(i.active&&r.active)}}function G0(){return{refreshed:[],skipped:[],warnings:[]}}async function B0(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?G0():fl(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function J0(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&an(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function V0(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 K0(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Xf(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:za(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:za(i,e.vector_store?.adapter??null)}}function Y0(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function X0(e,t,n){return e.enabled&&n.length>0&&t}async function Z0(e,t,n,i,r){let a=q0(t,e),o=await on(e),s=a.semanticRuntimeAvailable?Va(n,o.entries):[],c=await B0({pmRoot:e,snapshot:a,refreshPolicy:i,staleBefore:s}),d=await on(e),l=a.semanticRuntimeAvailable?Va(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=J0({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=V0({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=bs(s,r),h=bs(l,r),_=X0(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:Y0(i),...Xf(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:qf,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:K0(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 Q0(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 Zf(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new y("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var ex=new Set(["extensions","locks","search"]);function tx(e){let t=new Set(wc.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(vc));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of ex)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 nx(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:a}=tx(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 Ss(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 Qf(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 ix(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?nt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):it(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function ys(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function rx(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 ax(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 ox(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 xs=e=>e.unknown_event_count??0,Is=e=>e.actionable_unknown_event_count??xs(e);function sx(e,t,n,i,r,a){let o=xs(i),s=Is(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 eh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function cx(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 dx(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function lx(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 th(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=yo(i)?.code??Es(i),o=n.get(r)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a],d=ks(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 ux(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 mx(e){for(let t of e.checks){let n=wo(e.remediationSources[t.name]);ux({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function px(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 _s(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 fx(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 nh(e,t={}){let n=M(process.cwd(),e.path);await te(n);let i=Jt(n),{settings:r,warnings:a}=await Gd(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=Zf(t),m=await nx(n,s,c),f=Q0(r),p=await H0(r,{checkTelemetry:t.checkTelemetry===!0}),h=await C0(n,r,!!e.noExtensions),_=Qf(t),w=[],v=await ix({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=vr(pe(r.schema),v),x=[...(await Mu({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(de=>de.startsWith("agent_guidance_")),...f,...br(k)],D=_.skipDrift?{warnings:[]}:await zd({pmRoot:n,settings:r,itemIds:v.map(de=>de.id),commandLabel:"health"}),S=await y0(n,r.history.compact_policy,await _0(n)),b=await Jn(n,20,t.verboseAuthorEvents===!0),P=Is(b),I=P>0?[`history_unknown_author_events:${P}`]:[],A=eh(await _l(n,v,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),K=await ku(n),Se=K.warnings,he=await z0(n),me=_.skipIntegrity&&!l?{...ys("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await k0(n,s.type_to_folder,r.schema,r,l,v),Le=_.skipDrift?ys("history_drift"):await W0({pmRoot:n,items:E,settings:r,typeRegistry:s,itemReadWarnings:w}),xi=[...new Set(w)],$n=await px({gitWorkspaceRoot:me.gitWorkspaceRoot,pendingMergeReceipts:me.pendingMergeReceipts,historyDriftCheck:Le,global:e});fx(Le,$n);let U=_.skipVectors?ys("vectorization"):await Z0(n,r,E,u,t.verboseStaleItems===!0),q=[rx(i,r,o),ax(m,c),ox(x,k),p.check,h.check,sx(v,r,S,b,A.scan,K),he.check,me.check,Le.check,U.check],Ii=cx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:xi,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:S,authorAttributionWarnings:I,staleInProgressWarnings:A.warnings,provenanceWarnings:Se,locksCheck:he,integrityCheck:me,historyDriftCheck:Le,vectorizationCheck:U}),Ri=lx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:xi,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:S,authorAttributionWarnings:I,staleInProgressWarnings:A.warnings,provenanceWarnings:Se,locksCheck:he,integrityCheck:me,historyDriftCheck:Le,vectorizationCheck:U});mx({checks:q,remediationSources:Ri,historyDriftedCount:dx(Le),overThresholdCount:S.over_threshold.length});let Ea=Ii.filter(de=>!ks(de,l)),Sa=th({warnings:Ii,checks:q,remediationSources:Ri,requireMergeDrivers:l}),Q_=new Set(Sa.filter(de=>de.severity==="gate_failing").map(de=>de.check)),eg=new Set(Sa.map(de=>de.check));for(let de of q)de.ok=!Q_.has(de.name),eg.has(de.name)&&(de.status="warn");let tg={ok:Ea.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Ea.length>0?g.GENERIC_FAILURE:0},checks:q,warnings:Ii,findings:Sa,failed_because:Ea,generated_at:T()};return po(tg,t,_.summaryMode)}var Yj={buildHierarchyIntegrityWarnings:Jf,buildExtensionHealthTriageSummary:Vf,buildHealthFindings:th,buildCapabilityContractMetadata:di,buildStaleInProgressHealthSummary:eh,buildVectorizationProviderDetails:Xf,collectUnknownCapabilityGuidance:ci,isAdvisoryHealthWarning:ks,isDirectory:Ss,isExpectedUnmanagedExtension:ws,listItemDocumentPaths:Bf,normalizeEndpointForDisplay:ra,normalizeExtensionNameForMatch:En,parseTelemetryQueue:Kf,probeTelemetryEndpointHealth:Yf,projectHealthResult:po,resolveActionableUnknownAuthorEventCount:Is,resolveHealthSkipPolicy:Qf,resolveUnknownAuthorEventCount:xs,resolveVectorRefreshPolicy:Zf,selectStaleItemDetail:bs,summarizeHealthCheckDetails:uo,summarizeExtensionList:Kn,summarizeRecordList:je,summarizeStringList:z,telemetryEnvFlagEnabled:ia,warningCode:Es};(function(){try{var e=typeof window<"u"?window:typeof 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 ih(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!xl(e,t).ok)return{reason:"unverified_history"};let i=Yi(),r={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(i.metadata.status));i=Jd(i,o.patch,a+1,o.op),n.has(String(i.metadata.status))?s||(r=["create","close","cancel","update","update_audit"].includes(o.op)&&yt(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):r={reason:"no_proven_transition"}}return r}function rh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function ah(e,t,n,i,r){let a=rh(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 tt(Dt(e,d.id),d.id),{body:m,...f}=d;l=ih(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 oh(e,t){let n=M(process.cwd(),t.path),i=await $(n),r=pe(i.schema);await rt({pmRoot:n,settings:i,id:e.item_id,op:"update",author:W(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 tt(Dt(n,a.metadata.id),a.metadata.id),s=rh(r),c=ih(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new y("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",g.GENERIC_FAILURE);return a.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function hx(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function sh(e){return`${e.item_id} ${e.link_kind}`}function ch(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=hx(r.classification,i.classification),r.owners.set(sh(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[sh(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 dh(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=ch(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=Ji(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 Sn from"node:fs/promises";import xn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function _x(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let a;try{a=await Sn.readdir(xn.join(e,r))}catch{return}for(let o of a)for(let s of On)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 gx(e,t){let{id:n,relativePath:i,liveItemIds:r,out:a}=e,o=De(t);if(o){a.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=yx(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 yx(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 Rs(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 wx(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await Sn.readdir(xn.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 Sn.readFile(xn.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Rs("history stream",o)});continue}gx({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},a)}return n}function lh(e){let t=De(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 vx(e){let t=[],n=0,i=null;try{i=await B(Jt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Rs("configuration file",a)})}if(i!==null){n+=1;let a=lh(i);a!==null&&t.push({path:"settings.json",detail:a})}let r;try{r=await Sn.readdir(xn.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 Sn.readFile(xn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Rs("configuration file",c)});continue}let s=lh(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function uh(e,t,n,i={}){let r=await _x(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=xn.join(e,u.relativePath);return wt(await Sn.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 wx(e,a),l=await vx(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 ec from"node:fs/promises";import{realpathSync as PI}from"node:fs";import{execFile as LI}from"node:child_process";import Ee from"node:path";import{promisify as NI}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 bx=["metadata","resolution"],As=["metadata","resolution","estimates","timestamps","lifecycle"],kx="completed";function Cs(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function mh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function ph(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=mh(n.close_reason)??kx;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${Cs(i)}`,gate:"resolution"})}return t}function fh(e){let t=[];for(let n of e){let i=mh(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 ${Cs(i)}`,gate:"metadata"})}return t}function hh(e,t){return e.map(n=>{let i=qd(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 _h(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 gh(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 ${Cs(n.path)}`})}return t}function yh(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 y(`--fix-scope values must not be empty. Supported values: ${As.join(", ")}.`,g.USAGE);return new Set(bx)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(As.includes(r)){n.add(r);continue}throw new y(`Unknown --fix-scope value "${i}". Supported values: ${As.join(", ")}.`,g.USAGE)}return n}function wh(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 _i(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 Ex=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function Sx(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=Ex.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 vh(e){return typeof e=="string"&&e.trim().length>0}function xx(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 bh(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||vh(r.duplicate_of))continue;let a=Sx(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:vh(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=xx(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 kh(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 Eh(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Sh(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=Eh(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(Eh(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 xh(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 Ix=/^[a-z][a-z0-9+.-]+:\/\//i;function gi(e){return Ix.test(e.trim())}import Rx from"node:fs/promises";import ke from"node:path";import{glob as Ax}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 Cx=["path","scope","note"],Tx=["pattern","glob","path","scope","note"],$x=["path"],Dx=["from","to"],Ox=new Set(["note","scope"]);function Rh(e){let t=e??"project";if(!xa.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${xa.join(", ")} (default: project).`,g.USAGE);return t}function Ts(e){if(e.startsWith("```")||e.includes(`
@@ -62,4 +62,4 @@ ${a}`,g.GENERIC_FAILURE)}}function ka(e){return typeof e.tag=="string"&&e.tag.tr
62
62
  `);ae(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{ae(e.progressEnabled,"writing vectorization status ledger"),await pl(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 tW(e,t){let n=JA(e.mode),i=BA(e),r=e.full===!0;ae(i,`start mode=${n}`);let a=M(process.cwd(),t.path);await te(a);let o=ar(await $(a)).settings,s=null;try{s=await ie(a,Bd,o.locks.ttl_seconds,W(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===g.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=YA(o),d=XA(o),l=iC({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;ae(i,"loading item corpus");let m=await rC({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;ae(i,`loaded_items=${h.length}`);let _=T(),w=nC(u,_,h),v=Si.join(a,uc),E=Si.join(a,mc),k=u==="keyword"?await fc(a,p,o.schema,f):h,x=[],D={},S=null,b=tC(u);if(u==="keyword"&&await aC({pmRoot:a,settings:o,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let A=await mC({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:x,semanticSummary:b,progressEnabled:i});k=A.documentsForKeywordArtifacts,D=A.vectorizationLedgerEntries,S=A.vectorizationEmbeddingMetadata}let P=await pC({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:D,vectorizationEmbeddingMetadata:S,progressEnabled:i}),I=[...await V({path:v,scope:"project",op:"reindex:manifest"}),...await V({path:E,scope:"project",op:"reindex:embeddings"}),...await ji({mode:u,total_items:h.length})];return ae(i,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:uc,embeddings:mc},warnings:[...f,...x,...P,...I],generated_at:_}}finally{await s?.()}}export{L as a,we as b,Ve as c,ln as d,Ka as e,Tl as f,Mt as g,Ya as h,dg as i,Qa as j,eo as k,Pl as l,mn as m,zn as n,no as o,Ag as p,Ul as q,Wn as r,zl as s,hr as t,io as u,Wl as v,ql as w,Gl as x,sm as y,$g as z,AC as A,Vl as B,Pg as C,VC as D,Xw as E,ID as F,CD as G,TD as H,Qn as I,$D as J,DD as K,OD as L,PD as M,LD as N,ND as O,MD as P,jD as Q,FD as R,UD as S,HD as T,Bo as U,es as V,e$ as W,Mu as X,jg as Y,eu as Z,oT as _,Jn as $,sT as aa,Gg as ba,Bg as ca,cT as da,Jg as ea,Ah as fa,pT as ga,su as ha,Th as ia,lF as ja,uF as ka,Vn as la,yr as ma,du as na,lu as oa,uu as pa,mu as qa,_u as ra,yu as sa,wu as ta,ku as ua,At as va,vN as wa,bN as xa,kN as ya,EN as za,$N as Aa,wf as Ba,ta as Ca,tM as Da,mt as Ea,Af as Fa,nM as Ga,iM as Ha,HS as Ia,GS as Ja,Of as Ka,py as La,Su as Ma,_s as Na,YM as Oa,XM as Pa,vr as Qa,br as Ra,nh as Sa,Yj as Ta,ih as Ua,ah as Va,oh as Wa,dh as Xa,uh as Ya,lI as Za,uI as _a,hF as $a,_F as ab,gF as bb,yF as cb,pI as db,fI as eb,hI as fb,wF as gb,Oh as hb,gI as ib,Ph as jb,Ns as kb,Nh as lb,yI as mb,wI as nb,vI as ob,Mh as pb,Ms as qb,xF as rb,IF as sb,Hs as tb,zs as ub,MF as vb,jF as wb,FF as xb,ZI as yb,YU as zb,S_ as Ab,bi as Bb,R_ as Cb,A_ as Db,C_ as Eb,ic as Fb,oA as Gb,OH as Hb,nz as Ib,lz as Jb,z_ as Kb,W_ as Lb,q_ as Mb,Pz as Nb,Jz as Ob,Vz as Pb,Kz as Qb,tW as Rb};
65
- //# sourceMappingURL=chunk-T27TLSEU.js.map
65
+ //# sourceMappingURL=chunk-W2CND3BD.js.map