@unbrained/pm-cli 2026.9.14 → 2026.9.15

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 (74) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +12 -0
  3. package/dist/cli-bundle/bundle-manifest.json +148 -148
  4. package/dist/cli-bundle/chunks/{chunk-5JIJAWIF.js → chunk-3AHONKLL.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-DBHQIS6Z.js → chunk-3RB6Z7XE.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-ZYRN2OG3.js → chunk-5P5PYCZX.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-B6W5LIXK.js → chunk-BOZ4HVYL.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-J4DRE3WN.js +237 -0
  9. package/dist/cli-bundle/chunks/{chunk-GQMILIC5.js → chunk-RKPUO75B.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-O7SRS7Y3.js → chunk-RM2OGG65.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-D5AJQU7F.js → chunk-UKLOSZV6.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-XEV7BHH3.js → chunk-WDF7PP4P.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-A2Q64TGR.js → chunk-WLJJ4MAU.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-BY3ID7QI.js → chunk-Y2P3DSSO.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-NYE6EREL.js → chunk-YMMLKKEP.js} +2 -2
  16. package/dist/cli-bundle/chunks/{register-list-query-B2U36YWL.js → register-list-query-IWSPNFFD.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-mutation-GX42CQYR.js → register-mutation-3DVF4R64.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-operations-ZV34KX5E.js → register-operations-LXP3MECQ.js} +2 -2
  19. package/dist/cli-bundle/chunks/{register-setup-W4OS7IZW.js → register-setup-KFQSNBDX.js} +2 -2
  20. package/dist/cli-bundle/focused-chunks/{chunk-GGDO6VBT.js → chunk-4YTDKIPF.js} +17 -17
  21. package/dist/cli-bundle/focused-chunks/{chunk-ZFNRD7EN.js → chunk-533DCWPY.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/{chunk-FNLAQJES.js → chunk-5SBU4QDC.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-KWP3QTN7.js → chunk-63YRRGKX.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-N23WTRCC.js → chunk-6C3CUU2G.js} +3 -3
  25. package/dist/cli-bundle/focused-chunks/{chunk-ENJH7CBZ.js → chunk-AXDAIBT3.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-6WZBO4VQ.js → chunk-BMATJLPT.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-FHQLQOUZ.js → chunk-JKJYXCT6.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-D4FQV6TY.js → chunk-MD7ADLME.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-7BUJABHB.js → chunk-OGGF2RBL.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-CPQQIVDL.js → chunk-PBJC2ZNA.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-UFSMYVZF.js → chunk-SHF57M2H.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-C5NQVXKE.js → chunk-UACMCSCC.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-LFGTCEHX.js → chunk-YBQTVE5S.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-O4EROPO3.js → chunk-ZHX3433X.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-ZOE2NSJB.js +20 -0
  36. package/dist/cli-bundle/main.js +2 -2
  37. package/dist/cli-bundle/sdk-authoring.js +1 -1
  38. package/dist/cli-bundle/sdk-contracts.js +1 -1
  39. package/dist/cli-bundle/sdk-core.js +1 -1
  40. package/dist/cli-bundle/sdk-governance.js +1 -1
  41. package/dist/cli-bundle/sdk-graph.js +1 -1
  42. package/dist/cli-bundle/sdk-merge.js +40 -40
  43. package/dist/cli-bundle/sdk-query.js +1 -1
  44. package/dist/cli-bundle/sdk-runtime.js +1 -1
  45. package/dist/cli-bundle/sdk-testing.js +1 -1
  46. package/dist/cli-bundle/sdk.js +1 -1
  47. package/dist/core/extensions/index.d.ts +7 -0
  48. package/dist/core/extensions/index.js +1 -1
  49. package/dist/core/lock/lock.js +2 -2
  50. package/dist/core/telemetry/policy.d.ts +2 -0
  51. package/dist/core/telemetry/policy.js +1 -1
  52. package/dist/core/telemetry/read-sampling.d.ts +8 -0
  53. package/dist/core/telemetry/read-sampling.js +3 -0
  54. package/dist/core/telemetry/runtime.js +2 -2
  55. package/docs/CONFIGURATION.md +6 -2
  56. package/marketplace.json +2 -2
  57. package/package.json +1 -1
  58. package/packages/pm-beads/package.json +1 -1
  59. package/packages/pm-calendar/package.json +1 -1
  60. package/packages/pm-command-kit/package.json +1 -1
  61. package/packages/pm-digital-twin/package.json +1 -1
  62. package/packages/pm-governance-audit/package.json +1 -1
  63. package/packages/pm-guide-shell/package.json +1 -1
  64. package/packages/pm-kanban/package.json +1 -1
  65. package/packages/pm-lifecycle-hooks/package.json +1 -1
  66. package/packages/pm-linked-test-adapters/package.json +1 -1
  67. package/packages/pm-search-advanced/package.json +1 -1
  68. package/packages/pm-templates/package.json +1 -1
  69. package/packages/pm-todos/package.json +1 -1
  70. package/packages/pm-vcs/package.json +1 -1
  71. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  72. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  73. package/dist/cli-bundle/chunks/chunk-33PER336.js +0 -236
  74. package/dist/cli-bundle/focused-chunks/chunk-CMCSUANO.js +0 -20
@@ -1,4 +1,4 @@
1
- import{Da as y_,Ea as Yo,Fa as Xo,J as h_,Ja as v_,Oa as w_,Xa as Jo,e as a_,i as Xn,j as g_,q as wt,s as Er,t as Tr,ta as Ho,u as ln}from"./chunk-5JIJAWIF.js";import{A as Hn,Aa as Yn,Ab as I_,B as br,Ba as Vo,Bb as x_,C as Se,E as kr,Ea as b_,H as Sr,I as c_,K as Bo,L as d_,N as l_,Ob as R_,Ra as Jn,Ua as un,Wa as mn,Zc as N_,ad as D_,bb as k_,ga as u_,ha as m_,hb as S_,rb as E_,ub as T_,vb as Qn,yb as A_,yc as O_,z as Vn,za as __,zb as C_,zc as L_}from"./chunk-D5AJQU7F.js";import{$c as sl,$d as nn,$j as Q,$m as dm,Ac as Yi,Ag as Nl,Am as $u,An as Lm,Ba as wo,Bd as Pe,Bg as Io,Bi as dr,Bk as du,Bl as Su,Bm as Uu,Bn as Nm,Cb as $n,Cd as _l,Ci as qn,Cm as ju,Cn as Dm,Dd as Rt,Df as Sl,Di as Kn,Dk as lu,Dm as Gu,Dn as Mm,E as Ad,Ea as Mn,Em as qu,En as Pm,F as Cd,Fa as De,Fd as nr,Fh as Ul,Fm as Ku,Fn as Fm,Ga as zi,Gd as en,Gi as an,Gk as Oo,Gl as Eu,Gm as zu,Gn as $m,H as Id,Ha as Wi,Hd as _e,Hi as cn,Hl as Tu,Hm as Wu,Hn as Um,Ia as Md,Ib as Qd,Id as ir,Ig as Dl,Ii as Kl,Ik as uu,Im as Bu,In as jm,J as xd,Ja as Pd,Jc as nl,Jl as hr,Jm as Vu,Jn as Gm,Ka as Fd,Kb as Zd,Kd as To,Kk as mu,Kl as Au,Km as Hu,Kn as qo,L as Rd,La as $d,Le as bl,Lk as Bn,Lm as Yu,Ln as qm,M as Gi,Ma as Ud,Mb as xt,Mg as Ml,Mm as Xu,Mn as Km,N as Ct,Na as jd,Nj as eu,Nn as Ko,O as m,Oa as Gd,Ob as el,Oe as jn,Oi as yt,Om as Ju,On as zm,Oo as p_,Pa as bo,Pe as Gn,Pi as zl,Pm as jo,Pn as Wm,Q as p,Qj as tu,Qm as Qu,Qn as Bm,Qo as f_,Rc as M,Rg as xo,Ri as lr,Rj as nu,Rm as Zu,Rn as Vm,S as ne,Si as Wl,Sm as em,Sn as Hm,T as Od,Th as jl,Ti as ur,Tm as tm,Tn as vt,Ui as mr,Uj as iu,Um as nm,Un as Ym,Vi as _r,Vj as gr,Vm as im,Vn as Xm,Wc as il,Wj as ru,Wm as rm,Wn as Jm,Xa as ko,Xc as rl,Xd as rr,Xi as pr,Xm as sm,Xn as Qm,Ya as Pn,Ym as om,Z as Ld,Za as Ee,Zd as K,Ze as kl,Zm as am,Zn as Zm,_c as ot,_d as tn,_i as Bl,_j as P,_m as cm,ab as $,ad as Me,ak as be,an as lm,ba as R,bb as rt,bd as ol,be as sr,bf as Co,bg as El,bj as zn,bl as Lo,bn as um,bo as e_,ca as Nd,cb as Bi,cd as al,ce as pl,cf as G,ck as dn,cl as No,cn as mm,co as yr,da as yo,db as Jt,dd as cl,de as fl,df as sn,dk as ke,dl as Do,dm as Fo,dn as Go,do as t_,eb as Fn,ec as ie,ek as Ot,el as Mo,em as Cu,en as _m,eo as vr,f as Be,fa as qi,fb as It,fc as st,fe as gl,ff as on,fk as su,fn as pm,fo as n_,gc as tl,ge as or,gk as Wn,gl as _u,gn as fm,go as zo,h as B,ha as me,hm as Iu,hn as gm,i as Ui,ib as x,id as ht,ih as Pl,ik as ou,im as $o,in as hm,io as i_,j as Dn,jb as He,jd as Xi,je as ar,jh as Fl,ji as Gl,jk as le,jm as Lt,jn as ym,jo as r_,kb as Ye,kd as Ji,ke as se,ki as ql,kl as Po,kn as vm,lb as Te,ld as dl,le as Ao,lh as $l,lk as Ro,lm as xu,ln as wm,lo as s_,mb as qd,me as de,mg as Tl,mj as fr,mk as au,mn as bm,mo as wr,n as gt,nb as Kd,ne as rn,ng as Al,nl as pu,nn as km,o as Z,ob as Qt,oe as hl,og as Cl,on as Sm,p as ji,pb as Vi,pd as Qi,pg as Il,pj as Vl,pl as fu,q as W,qa as Ki,qb as zd,qd as Zi,qe as cr,qg as xl,qj as Hl,ql as gu,qm as Uo,r as ee,ra as vo,rb as Wd,rd as er,re as yl,rg as Rl,rj as Yl,rl as hu,s as Ve,sb as So,sd as ll,se as vl,sg as Xe,sj as Xl,sl as yu,sm as Ru,sn as Em,so as Wo,t as Ed,tb as Eo,td as tr,tg as Ol,tm as Ou,tn as Tm,u as Td,ub as Bd,ud as ul,um as Lu,un as Am,va as Dd,vb as Vd,vd as J,vj as Jl,vm as Nu,vn as Cm,wb as Hd,wd as Zt,wj as I,wk as cu,wl as vu,wm as Du,wn as Im,wo as o_,xb as Yd,xd as Un,xf as at,xj as Ql,xl as wu,xm as Mu,xn as xm,yb as Xd,yc as Hi,yd as he,ye as wl,yj as Zl,yl as bu,ym as Pu,yn as Rm,zb as Jd,zd as ml,zg as Ll,zl as ku,zm as Fu,zn as Om}from"./chunk-33PER336.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]="00d2200c-d308-51a6-acc4-8da90afaf6d6")}catch{}})();var N=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Re=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Je=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 _n(e){try{return await e()}catch(t){throw t instanceof N?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function M_(e){try{return await e()}catch(t){throw t instanceof Re?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Yw}from"node:crypto";import Xw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var pn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00ad9b34-4feb-5812-8755-801869cce3ad")}catch{}})();var F_=1,ct=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Zn=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Jw=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Qw=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Ar=30,Cr=5e3,$_=4,Zw=50;function dt(e,t){if(!Qw.test(e))throw new N(`${t} must be a stable lowercase id`)}function eb(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function ei(e){let t=Jw.filter(r=>e[r]!==void 0);if(t.length!==1)throw new N(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function Zo(e,t){return ie(e)===ie(t)}function U_(e,t){if(t.polarity==="equals")return Zo(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 j_(e){let t=ei(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>U_(i.observed,t)===(i.expected==="pass"))}function tb(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!Zo(e.value,t.value)}function nb(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||ie(e.scope)!==ie(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return tb(ei(e),ei(t))||n[t.enforcement]<n[e.enforcement]||i}function ib(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new N("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 N("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new N("items source equals/state requires field")}function rb(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new N("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new N("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 N("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 N("dependency_kind source source_kind_state must be present or missing")}function sb(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new N("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 N("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 N("prose_edge_gap exemption selectors must not be empty")}}function ea(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&eb(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new N(`measurement.source.kind must be one of ${Zn.join(", ")}`);let n=Reflect.get(t,"kind");if(!Zn.includes(n))throw new N(`measurement.source.kind must be one of ${Zn.join(", ")}`);let i=t;if(i.kind==="items"&&ib(i),i.kind==="dependency_kind"&&rb(i),i.kind==="prose_edge_gap"&&sb(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new N(`${i.kind} source requires field`);return i.kind==="provider"&&(dt(i.provider,"provider source provider"),dt(i.key,"provider source key")),e}function ta(e){if(dt(e.id,"assertion.id"),dt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new N("assertion.owner_item_id is required");let t=ei(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new N(`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 N("retired assertion requires retire_reason");e.scope.kind==="filter"&&dt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new N("assertion negative control requires pass and fail cases");if(!j_(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function ob(e){if(!Array.isArray(e.allowed_providers))throw new N("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)dt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new N("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!ct.includes(t))throw new N(`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 N(`gate provider policy trigger ${t} is invalid`)}}function G_(e){if(dt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new N("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new N("gate requires at least one assertion");for(let t of e.assertion_ids)dt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new N(`gate.triggers is required and must be an array of ${ct.join(", ")}`);if(e.triggers.length===0)throw new N("gate requires at least one trigger");for(let t of e.triggers)if(!ct.includes(t))throw new N(`gate trigger must be one of ${ct.join(", ")}`);return e.provider_policy&&ob(e.provider_policy),e}function fn(e){if(e.version!==F_)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(ea(i),t.has(`measurement:${i.id}`))throw new N(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(ta(i),t.has(`assertion:${i.id}`))throw new N(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){G_(i);let r=i.assertion_ids.filter(s=>!e.assertions.some(o=>o.id===s));if(r.length>0)throw new N(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new N(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of q_(e))if(!n.has(i))throw new N(`${r.join(", ")} references missing measurement ${i}`);return e}function na(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)na(n,t)}function q_(e){let t=new Map,n=(i,r)=>{let s=t.get(i)??[];s.push(r),t.set(i,s)};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=[];na(i.source.expression,r);for(let s of r)n(s,`derived measurement ${i.id}`)}return t}function ab(e,t){let n=e.assertion_ids.flatMap(s=>{let o=t.assertions.find(a=>a.id===s);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let s=n.pop();if(i.has(s))continue;i.add(s);let o=t.measurements.find(a=>a.id===s);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&na(o.source.expression,n)}return r}function ti(){return{version:F_,measurements:[],assertions:[],gates:[]}}function cb(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 s=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?s:!s}return Zo(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function db(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 lb(e,t){let n=[],i=xt(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let s of r.dependencies??[]){let o=xt(s.kind)??s.kind.trim().toLowerCase(),a=s.source_kind?.trim();o===i&&db(e,a)&&n.push(`${r.id}->${s.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function ub(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 s=Reflect.get(r,"text");typeof s=="string"&&t.push(s)}}}return t}function mb(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 Qo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function _b(e){let t=new Map,n=new Set,i=[],r=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,s=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let a of o.dependencies??[])n.add(Qo(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(Qo(o.id,a));for(let a of ub(o)){let c=[...a.matchAll(r)].map(d=>d[0]);s+=c.length,i.push({holder_id:o.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:s}}function pb(e,t){let n=_b(t.items),i=new Map;for(let o of n.prose_mentions){let a=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(a)];for(let d of c){let l=Qo(o.holder_id,d);if(n.linked_pairs.has(l)||mb(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(_=>_!==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()],s=r.map(o=>o.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function fb(e,t){return{value:t.history.filter(i=>(e.op===void 0||i.op===e.op)&&(e.author===void 0||i.author===e.author)&&(e.harness===void 0||i.agent_harness===e.harness)&&(e.model===void 0||i.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function gb(e,t){let n=t.items.filter(i=>{let r=i[e.link],s=Array.isArray(r)&&r.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function hb(e,t){let n=e.source;return n.kind==="items"?cb(n,t):n.kind==="dependency_kind"?lb(n,t):n.kind==="prose_edge_gap"?pb(n,t):n.kind==="history"?fb(n,t):n.kind==="links"?gb(n,t):null}function K_(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 yb(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 z_(e,t,n){let i=new Array(e.length),r=0,s=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(s),i}async function W_(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 a=await B_(o,t,n,i,r);if(typeof a.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[a.cost];return r.charged.add(o.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let s=await z_(e.operands,$_,o=>W_(o,t,n,i,r));return{value:yb(e.operator,s.map(o=>o.value)),costs:s.flatMap(o=>o.costs),population_size:Math.max(0,...s.map(o=>o.population_size)),contributors:[...new Set(s.flatMap(o=>o.contributors))]}}async function vb(e,t,n,i,r){ea(e);let s=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await W_(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=hb(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()-s},l=K_([...a,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Re(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${Yw("sha256").update(ie(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function B_(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let s=r.cache.get(e.id);if(s)return s;let o=vb(e,t,n,i,r).catch(a=>{if(a instanceof Je&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new Je(a.message,c);throw d.cause=a,d}throw a});return r.cache.set(e.id,o),o}async function ia(e,t,n=[e]){return B_(e,t,n,[],{cache:new Map,charged:new Set})}function wb(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==="monotone_nondecreasing",e-t.value)}function bb(e,t,n={}){ta(e);let i=ei(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:wb(t.value,i),verdict:r?"retired":U_(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:j_(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function kb(e,t,n,i){let r=ab(e,t);if(r.size===0)return;let s=e.provider_policy,o=s?.triggers[i];if(!s||!o)throw new Re(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let a=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!a.has(d))throw new Re(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Re(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new Re(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new Re(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function P_(e,t,n,i,r){try{return await ia(n,i,r)}catch(s){if(s instanceof Je){let o=s.check?` check ${s.check}`:"",a=s.measurement_id??n.id,c=new Re(`assurance gate ${e} assertion ${t} measurement ${a} source ${s.source_kind}${o} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function V_(e,t,n,i){fn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new Re(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new Re(`assurance gate ${e} does not declare trigger ${i.trigger}`);kb(r,t,n,i.trigger);let s=await z_(r.assertion_ids,$_,async c=>{let d=t.assertions.find(g=>g.id===c),l=t.measurements.find(g=>g.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let g=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!g.has(h.status))}}else if(d.scope.kind==="filter"){let g=d.scope.measurement_id,h=t.measurements.find(w=>w.id===g),y=await P_(r.id,d.id,h,n,t.measurements),v=new Set(y.contributors);u={...n,items:n.items.filter(w=>v.has(w.id))}}let _=n.items.find(g=>g.id===d.owner_item_id),f=_!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(_.status);return bb(d,await P_(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=s.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":a?"warn":"pass",exit_code:o?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:K_(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Ir(e){return Xw.join(e,"assurance.json")}async function H_(e){let t=await ee(Ir(e));return t===null?ti():xr(t)}function xr(e){try{return fn(JSON.parse(e))}catch(t){throw new p("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.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 Rr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Sb(e,t){e==="measurement"?ea(t):e==="assertion"?ta(t):G_(t)}async function ni(e,t){let n=structuredClone(Rr(await H_(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function ra(e,t,n){let i=Rr(await H_(e),t).find(r=>r.id===n);if(!i)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(i)}async function Or(e,t,n,i={}){Sb(t,n);let r=await I(e),s=G(i.author,r.author_default),o=await cn({pmRoot:e,filePath:Ir(e),op:`assurance:${t}:put`,author:s,message:i.message,lockTtlSeconds:Ar,lockWaitMs:Cr,mutate:a=>{let c=a===null?ti():xr(a),d=Rr(c,t),l=d.findIndex(_=>_.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&nb(d[l],n)){let _=n.authorization_decision;if(!_||!i.authorized_decision_ids?.includes(_))throw new N(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),fn(c),{raw:`${JSON.stringify(c,null,2)}
1
+ import{Da as y_,Ea as Yo,Fa as Xo,J as h_,Ja as v_,Oa as w_,Xa as Jo,e as a_,i as Xn,j as g_,q as wt,s as Er,t as Tr,ta as Ho,u as ln}from"./chunk-3AHONKLL.js";import{A as Hn,Aa as Yn,Ab as I_,B as br,Ba as Vo,Bb as x_,C as Se,E as kr,Ea as b_,H as Sr,I as c_,K as Bo,L as d_,N as l_,Ob as R_,Ra as Jn,Ua as un,Wa as mn,Zc as N_,ad as D_,bb as k_,ga as u_,ha as m_,hb as S_,rb as E_,ub as T_,vb as Qn,yb as A_,yc as O_,z as Vn,za as __,zb as C_,zc as L_}from"./chunk-UKLOSZV6.js";import{$c as sl,$d as nn,$j as Q,$m as dm,Ac as Yi,Ag as Nl,Am as $u,An as Lm,Ba as wo,Bd as Pe,Bg as Io,Bi as dr,Bk as du,Bl as Su,Bm as Uu,Bn as Nm,Cb as $n,Cd as _l,Ci as qn,Cm as ju,Cn as Dm,Dd as Rt,Df as Sl,Di as Kn,Dk as lu,Dm as Gu,Dn as Mm,E as Ad,Ea as Mn,Em as qu,En as Pm,F as Cd,Fa as De,Fd as nr,Fh as Ul,Fm as Ku,Fn as Fm,Ga as zi,Gd as en,Gi as an,Gk as Oo,Gl as Eu,Gm as zu,Gn as $m,H as Id,Ha as Wi,Hd as _e,Hi as cn,Hl as Tu,Hm as Wu,Hn as Um,Ia as Md,Ib as Qd,Id as ir,Ig as Dl,Ii as Kl,Ik as uu,Im as Bu,In as jm,J as xd,Ja as Pd,Jc as nl,Jl as hr,Jm as Vu,Jn as Gm,Ka as Fd,Kb as Zd,Kd as To,Kk as mu,Kl as Au,Km as Hu,Kn as qo,L as Rd,La as $d,Le as bl,Lk as Bn,Lm as Yu,Ln as qm,M as Gi,Ma as Ud,Mb as xt,Mg as Ml,Mm as Xu,Mn as Km,N as Ct,Na as jd,Nj as eu,Nn as Ko,O as m,Oa as Gd,Ob as el,Oe as jn,Oi as yt,Om as Ju,On as zm,Oo as p_,Pa as bo,Pe as Gn,Pi as zl,Pm as jo,Pn as Wm,Q as p,Qj as tu,Qm as Qu,Qn as Bm,Qo as f_,Rc as M,Rg as xo,Ri as lr,Rj as nu,Rm as Zu,Rn as Vm,S as ne,Si as Wl,Sm as em,Sn as Hm,T as Od,Th as jl,Ti as ur,Tm as tm,Tn as vt,Ui as mr,Uj as iu,Um as nm,Un as Ym,Vi as _r,Vj as gr,Vm as im,Vn as Xm,Wc as il,Wj as ru,Wm as rm,Wn as Jm,Xa as ko,Xc as rl,Xd as rr,Xi as pr,Xm as sm,Xn as Qm,Ya as Pn,Ym as om,Z as Ld,Za as Ee,Zd as K,Ze as kl,Zm as am,Zn as Zm,_c as ot,_d as tn,_i as Bl,_j as P,_m as cm,ab as $,ad as Me,ak as be,an as lm,ba as R,bb as rt,bd as ol,be as sr,bf as Co,bg as El,bj as zn,bl as Lo,bn as um,bo as e_,ca as Nd,cb as Bi,cd as al,ce as pl,cf as G,ck as dn,cl as No,cn as mm,co as yr,da as yo,db as Jt,dd as cl,de as fl,df as sn,dk as ke,dl as Do,dm as Fo,dn as Go,do as t_,eb as Fn,ec as ie,ek as Ot,el as Mo,em as Cu,en as _m,eo as vr,f as Be,fa as qi,fb as It,fc as st,fe as gl,ff as on,fk as su,fn as pm,fo as n_,gc as tl,ge as or,gk as Wn,gl as _u,gn as fm,go as zo,h as B,ha as me,hm as Iu,hn as gm,i as Ui,ib as x,id as ht,ih as Pl,ik as ou,im as $o,in as hm,io as i_,j as Dn,jb as He,jd as Xi,je as ar,jh as Fl,ji as Gl,jk as le,jm as Lt,jn as ym,jo as r_,kb as Ye,kd as Ji,ke as se,ki as ql,kl as Po,kn as vm,lb as Te,ld as dl,le as Ao,lh as $l,lk as Ro,lm as xu,ln as wm,lo as s_,mb as qd,me as de,mg as Tl,mj as fr,mk as au,mn as bm,mo as wr,n as gt,nb as Kd,ne as rn,ng as Al,nl as pu,nn as km,o as Z,ob as Qt,oe as hl,og as Cl,on as Sm,p as ji,pb as Vi,pd as Qi,pg as Il,pj as Vl,pl as fu,q as W,qa as Ki,qb as zd,qd as Zi,qe as cr,qg as xl,qj as Hl,ql as gu,qm as Uo,r as ee,ra as vo,rb as Wd,rd as er,re as yl,rg as Rl,rj as Yl,rl as hu,s as Ve,sb as So,sd as ll,se as vl,sg as Xe,sj as Xl,sl as yu,sm as Ru,sn as Em,so as Wo,t as Ed,tb as Eo,td as tr,tg as Ol,tm as Ou,tn as Tm,u as Td,ub as Bd,ud as ul,um as Lu,un as Am,va as Dd,vb as Vd,vd as J,vj as Jl,vm as Nu,vn as Cm,wb as Hd,wd as Zt,wj as I,wk as cu,wl as vu,wm as Du,wn as Im,wo as o_,xb as Yd,xd as Un,xf as at,xj as Ql,xl as wu,xm as Mu,xn as xm,yb as Xd,yc as Hi,yd as he,ye as wl,yj as Zl,yl as bu,ym as Pu,yn as Rm,zb as Jd,zd as ml,zg as Ll,zl as ku,zm as Fu,zn as Om}from"./chunk-J4DRE3WN.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]="00d2200c-d308-51a6-acc4-8da90afaf6d6")}catch{}})();var N=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Re=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Je=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 _n(e){try{return await e()}catch(t){throw t instanceof N?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function M_(e){try{return await e()}catch(t){throw t instanceof Re?new p(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Yw}from"node:crypto";import Xw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var pn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00ad9b34-4feb-5812-8755-801869cce3ad")}catch{}})();var F_=1,ct=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Zn=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Jw=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Qw=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Ar=30,Cr=5e3,$_=4,Zw=50;function dt(e,t){if(!Qw.test(e))throw new N(`${t} must be a stable lowercase id`)}function eb(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function ei(e){let t=Jw.filter(r=>e[r]!==void 0);if(t.length!==1)throw new N(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function Zo(e,t){return ie(e)===ie(t)}function U_(e,t){if(t.polarity==="equals")return Zo(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 j_(e){let t=ei(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>U_(i.observed,t)===(i.expected==="pass"))}function tb(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!Zo(e.value,t.value)}function nb(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||ie(e.scope)!==ie(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return tb(ei(e),ei(t))||n[t.enforcement]<n[e.enforcement]||i}function ib(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new N("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 N("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new N("items source equals/state requires field")}function rb(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new N("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new N("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 N("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 N("dependency_kind source source_kind_state must be present or missing")}function sb(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new N("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 N("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 N("prose_edge_gap exemption selectors must not be empty")}}function ea(e){dt(e.id,"measurement.id"),e.max_cost!==void 0&&eb(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new N(`measurement.source.kind must be one of ${Zn.join(", ")}`);let n=Reflect.get(t,"kind");if(!Zn.includes(n))throw new N(`measurement.source.kind must be one of ${Zn.join(", ")}`);let i=t;if(i.kind==="items"&&ib(i),i.kind==="dependency_kind"&&rb(i),i.kind==="prose_edge_gap"&&sb(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new N(`${i.kind} source requires field`);return i.kind==="provider"&&(dt(i.provider,"provider source provider"),dt(i.key,"provider source key")),e}function ta(e){if(dt(e.id,"assertion.id"),dt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new N("assertion.owner_item_id is required");let t=ei(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new N(`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 N("retired assertion requires retire_reason");e.scope.kind==="filter"&&dt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new N("assertion negative control requires pass and fail cases");if(!j_(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function ob(e){if(!Array.isArray(e.allowed_providers))throw new N("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)dt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new N("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!ct.includes(t))throw new N(`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 N(`gate provider policy trigger ${t} is invalid`)}}function G_(e){if(dt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new N("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new N("gate requires at least one assertion");for(let t of e.assertion_ids)dt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new N(`gate.triggers is required and must be an array of ${ct.join(", ")}`);if(e.triggers.length===0)throw new N("gate requires at least one trigger");for(let t of e.triggers)if(!ct.includes(t))throw new N(`gate trigger must be one of ${ct.join(", ")}`);return e.provider_policy&&ob(e.provider_policy),e}function fn(e){if(e.version!==F_)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(ea(i),t.has(`measurement:${i.id}`))throw new N(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(ta(i),t.has(`assertion:${i.id}`))throw new N(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){G_(i);let r=i.assertion_ids.filter(s=>!e.assertions.some(o=>o.id===s));if(r.length>0)throw new N(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new N(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of q_(e))if(!n.has(i))throw new N(`${r.join(", ")} references missing measurement ${i}`);return e}function na(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)na(n,t)}function q_(e){let t=new Map,n=(i,r)=>{let s=t.get(i)??[];s.push(r),t.set(i,s)};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=[];na(i.source.expression,r);for(let s of r)n(s,`derived measurement ${i.id}`)}return t}function ab(e,t){let n=e.assertion_ids.flatMap(s=>{let o=t.assertions.find(a=>a.id===s);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let s=n.pop();if(i.has(s))continue;i.add(s);let o=t.measurements.find(a=>a.id===s);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&na(o.source.expression,n)}return r}function ti(){return{version:F_,measurements:[],assertions:[],gates:[]}}function cb(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 s=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?s:!s}return Zo(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function db(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 lb(e,t){let n=[],i=xt(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let s of r.dependencies??[]){let o=xt(s.kind)??s.kind.trim().toLowerCase(),a=s.source_kind?.trim();o===i&&db(e,a)&&n.push(`${r.id}->${s.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function ub(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 s=Reflect.get(r,"text");typeof s=="string"&&t.push(s)}}}return t}function mb(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 Qo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function _b(e){let t=new Map,n=new Set,i=[],r=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,s=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let a of o.dependencies??[])n.add(Qo(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(Qo(o.id,a));for(let a of ub(o)){let c=[...a.matchAll(r)].map(d=>d[0]);s+=c.length,i.push({holder_id:o.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:s}}function pb(e,t){let n=_b(t.items),i=new Map;for(let o of n.prose_mentions){let a=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(a)];for(let d of c){let l=Qo(o.holder_id,d);if(n.linked_pairs.has(l)||mb(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(_=>_!==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()],s=r.map(o=>o.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function fb(e,t){return{value:t.history.filter(i=>(e.op===void 0||i.op===e.op)&&(e.author===void 0||i.author===e.author)&&(e.harness===void 0||i.agent_harness===e.harness)&&(e.model===void 0||i.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function gb(e,t){let n=t.items.filter(i=>{let r=i[e.link],s=Array.isArray(r)&&r.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function hb(e,t){let n=e.source;return n.kind==="items"?cb(n,t):n.kind==="dependency_kind"?lb(n,t):n.kind==="prose_edge_gap"?pb(n,t):n.kind==="history"?fb(n,t):n.kind==="links"?gb(n,t):null}function K_(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 yb(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 z_(e,t,n){let i=new Array(e.length),r=0,s=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(s),i}async function W_(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 a=await B_(o,t,n,i,r);if(typeof a.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[a.cost];return r.charged.add(o.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let s=await z_(e.operands,$_,o=>W_(o,t,n,i,r));return{value:yb(e.operator,s.map(o=>o.value)),costs:s.flatMap(o=>o.costs),population_size:Math.max(0,...s.map(o=>o.population_size)),contributors:[...new Set(s.flatMap(o=>o.contributors))]}}async function vb(e,t,n,i,r){ea(e);let s=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await W_(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=hb(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()-s},l=K_([...a,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Re(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${Yw("sha256").update(ie(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function B_(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let s=r.cache.get(e.id);if(s)return s;let o=vb(e,t,n,i,r).catch(a=>{if(a instanceof Je&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new Je(a.message,c);throw d.cause=a,d}throw a});return r.cache.set(e.id,o),o}async function ia(e,t,n=[e]){return B_(e,t,n,[],{cache:new Map,charged:new Set})}function wb(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==="monotone_nondecreasing",e-t.value)}function bb(e,t,n={}){ta(e);let i=ei(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:wb(t.value,i),verdict:r?"retired":U_(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:j_(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function kb(e,t,n,i){let r=ab(e,t);if(r.size===0)return;let s=e.provider_policy,o=s?.triggers[i];if(!s||!o)throw new Re(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let a=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!a.has(d))throw new Re(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Re(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new Re(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new Re(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function P_(e,t,n,i,r){try{return await ia(n,i,r)}catch(s){if(s instanceof Je){let o=s.check?` check ${s.check}`:"",a=s.measurement_id??n.id,c=new Re(`assurance gate ${e} assertion ${t} measurement ${a} source ${s.source_kind}${o} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function V_(e,t,n,i){fn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new Re(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new Re(`assurance gate ${e} does not declare trigger ${i.trigger}`);kb(r,t,n,i.trigger);let s=await z_(r.assertion_ids,$_,async c=>{let d=t.assertions.find(g=>g.id===c),l=t.measurements.find(g=>g.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let g=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!g.has(h.status))}}else if(d.scope.kind==="filter"){let g=d.scope.measurement_id,h=t.measurements.find(w=>w.id===g),y=await P_(r.id,d.id,h,n,t.measurements),v=new Set(y.contributors);u={...n,items:n.items.filter(w=>v.has(w.id))}}let _=n.items.find(g=>g.id===d.owner_item_id),f=_!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(_.status);return bb(d,await P_(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=s.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":a?"warn":"pass",exit_code:o?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:K_(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Ir(e){return Xw.join(e,"assurance.json")}async function H_(e){let t=await ee(Ir(e));return t===null?ti():xr(t)}function xr(e){try{return fn(JSON.parse(e))}catch(t){throw new p("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.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 Rr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Sb(e,t){e==="measurement"?ea(t):e==="assertion"?ta(t):G_(t)}async function ni(e,t){let n=structuredClone(Rr(await H_(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function ra(e,t,n){let i=Rr(await H_(e),t).find(r=>r.id===n);if(!i)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(i)}async function Or(e,t,n,i={}){Sb(t,n);let r=await I(e),s=G(i.author,r.author_default),o=await cn({pmRoot:e,filePath:Ir(e),op:`assurance:${t}:put`,author:s,message:i.message,lockTtlSeconds:Ar,lockWaitMs:Cr,mutate:a=>{let c=a===null?ti():xr(a),d=Rr(c,t),l=d.findIndex(_=>_.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&nb(d[l],n)){let _=n.authorization_decision;if(!_||!i.authorized_decision_ids?.includes(_))throw new N(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),fn(c),{raw:`${JSON.stringify(c,null,2)}
2
2
  `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function sa(e,t,n={}){let i=ti();i.measurements=structuredClone(t.measurements),i.assertions=structuredClone(t.assertions),i.gates=structuredClone(t.gates),fn(i);let r=await I(e),s=G(n.author,r.author_default),o=await cn({pmRoot:e,filePath:Ir(e),op:"assurance:bundle:apply",author:s,message:n.message,lockTtlSeconds:Ar,lockWaitMs:Cr,mutate:a=>{let c=a===null?ti():xr(a),d=[],l=[],u=(_,f,g)=>{for(let h of f){let y=_.find(v=>v.id===h.id);if(!y){_.push(structuredClone(h)),d.push(`${g}:${h.id}`);continue}if(ie(y)!==ie(h))throw new N(`assurance bundle refuses to replace divergent ${g} ${h.id}`);l.push(`${g}:${h.id}`)}};return u(c.measurements,i.measurements,"measurement"),u(c.assertions,i.assertions,"assertion"),u(c.gates,i.gates,"gate"),fn(c),{raw:`${JSON.stringify(c,null,2)}
3
3
  `,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Y_(e,t,n,i={}){let r=await I(e),s=G(i.author,r.author_default),o=await cn({pmRoot:e,filePath:Ir(e),op:`assurance:${t}:remove`,author:s,message:i.message,lockTtlSeconds:Ar,lockWaitMs:Cr,mutate:a=>{let c=a===null?ti():xr(a);if(t==="measurement"){let u=q_(c).get(n);if(u&&u.length>0)throw new N(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new N(`assurance assertion ${n} is referenced by gate`);let d=Rr(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new N(`assurance ${t} ${n} not found`);return d.splice(l,1),fn(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 X_(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await I(e);await an({pmRoot:e,op:"assurance:gate:verdict",author:G(n.author,i.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Ar,lockWaitMs:Cr})}async function J_(e,t={}){let n=t.limit??Zw;if(!Number.isInteger(n)||n<1||n>pn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${pn}`);return(await on(Kn(e),qn)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7470da18-4b85-5090-8ede-7de708b1f4ff")}catch{}})();var ii=["software-delivery","research","agent-evaluation","operations"];function Q_(e,t,n,i,r){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:i,lifetime:"hold",enforcement:r,negative_control:{cases:[{observed:i,expected:"pass"},{observed:i+1,expected:"fail"}]}}}function Lr(e,t,n,i,r){let s=`preset-${e}`,o=r.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=o.map(c=>Q_(`${c.id}-zero`,c.id,i,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:a,gates:[{id:`${s}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Nr(e,t){return e==="software-delivery"?Lr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Lr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Lr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Lr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Z_(e,t,n,i={}){return sa(e,Nr(t,n).declarations,i)}async function ep(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),i={...e,items:e.items.filter(s=>!n.has(s.status))};return await Promise.all(["files","tests","docs"].map(async s=>{let o={id:`derived-active-missing-${s}`,description:`Observed active items missing ${s} evidence.`,source:{kind:"links",link:s,state:"missing"}},c=(await ia(o,i)).value,d=Q_(`${o.id}-ceiling`,o.id,t,c,"observe"),l=`active-missing-${s}`;return{id:l,population_size:i.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[o],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${s} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function tp(e,t,n={}){return sa(e,{measurements:t.flatMap(i=>i.declarations.measurements),assertions:t.flatMap(i=>i.declarations.assertions),gates:t.flatMap(i=>i.declarations.gates)},n)}async function np(e,t,n,i={}){let r=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==r)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${r}`);return Or(e,"assertion",{...t,enforcement:n},{...i,message:i.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import sp from"node:fs/promises";import{createRequire as Eb}from"node:module";import Oe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a0014621-9e3d-5620-8f36-081811054843")}catch{}})();function ip(e,t){let n=Oe.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Oe.sep}`)&&!Oe.isAbsolute(n))return n.split(Oe.sep).join("/");let i=Oe.resolve(e),r=0xcbf29ce484222325n;for(let o=0;o<i.length;o+=1)r^=BigInt(i.charCodeAt(o)),r=BigInt.asUintN(64,r*0x100000001b3n);return`<external>/${r.toString(16).padStart(16,"0")}/${Oe.basename(Oe.dirname(e))}/package.json`}function Tb(e){return e.includes(`${Oe.sep}.pnpm${Oe.sep}`)?"pnpm":e.includes(`${Oe.sep}node_modules${Oe.sep}`)?"npm":"other"}async function rp(e){try{let t=JSON.parse(await sp.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function oa(e){try{return await sp.realpath(e)}catch{return Oe.resolve(e)}}async function op(e,t,n=Dd(import.meta.url,["../../.."])){let i=await oa(t),r=await oa(Oe.join(n,"package.json")),s=await rp(r),o=new Map;s!==void 0&&o.set(r,{version:s,path:ip(r,i),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Eb(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await oa(l),_=await rp(u);if(_===void 0)continue;let f=u,g=o.get(f);if(g){g.consumers.includes(d.name)||(g.consumers.push(d.name),g.consumers.sort((h,y)=>h.localeCompare(y)));continue}o.set(f,{version:_,path:ip(u,i),layout:Tb(u),consumers:[d.name]})}catch{}let a=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:a.filter(d=>d.version!==s);return{host_version:s??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${s}:${d.version}:${d.consumers.join("+")}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fb87ff0c-88c8-52f9-9dc3-f37fec674425")}catch{}})();var Ab=Symbol("pm.mcp-mutation-transport"),Cb=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Mr(e){return Ab in e}function Pr(e,t){return Mr(e)?ml(t):Pe(e,t)}function da(e,t,n=[]){let i=Pe(e,{...e,...t});for(let r of n)Reflect.deleteProperty(i,r);return i}function O(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function re(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function yP(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function la(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new p(`${t} must be a finite integer.`,m.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new p(`${t} must be a finite integer.`,m.USAGE);return n}}function vP(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:O(e,"limit")??O(t,"limit")}function wP(e){let t=O(e,"outputFormat");return{json:!0,quiet:!0,author:O(e,"author"),path:O(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:O(e,"outputInclude"),outputLimit:re(e,"outputLimit"),outputBudget:re(e,"outputBudget"),outputSession:O(e,"outputSession"),outputCursor:O(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Ib=new Set(["tags","blockedBy","blocked_by","skills","fields"]),cp=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),xb=new Set([...cp].filter(e=>e!=="file")),Rb=new Set(["files","files-discover","docs","test","test-all"]),dp=new Set(["comments","notes","learnings"]);function Ob(e,t){if(!(!dp.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new p(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var Lb=new Set(["claim","release","start-task","pause-task","close-task"]),Nb={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun"],package:["dryRun"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Db=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function lp(e,t=""){let n={},i=Rb.has(t),r=t==="files"||t==="files-discover"||t==="docs",s=dp.has(t)?xb:cp;for(let[o,a]of Object.entries(e)){if(Array.isArray(a)&&Ib.has(o)){n[o]=a.join(",");continue}if(o==="note"&&r){n[o]=a;continue}if(typeof a=="string"&&s.has(o)){n[o]=[a];continue}if(typeof a=="string"&&i&&(o==="add"||o==="remove")){n[o]=[a];continue}n[o]=a}return n}function Mb(e,t,n){let i=O(e,"author");return i!==void 0?i:n!==void 0&&Lb.has(n)?O(e,"assignee")??O(t,"assignee"):void 0}function Pb(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function bP(e,t){let n=gn(e.options)?e.options:void 0,i=Ld(e.options),r={},s=c=>{i[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Nb[t??""]??[])s(c);for(let c of Db)s(c);t!==void 0&&Mr(e)&&Ob(t,i);let o=lp({...r,...i},t);if(t==="history-attest"&&Mr(e)&&(o.output!==void 0||typeof o.verify=="string"))throw new p("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",m.USAGE);let a=Mr(e)?e:n??e;return Pr(a,Pb(o,Mb(e,o,t)))}function kP(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function SP(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function Fb(e){let t=[],n=!0;for(let i of e.trim().toLowerCase()){if(i>="a"&&i<="z"||i>="0"&&i<="9"){t.push(i),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function EP(e){return!Cb.has(Fb(e))}function TP(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function ua(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function AP(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),i={};for(let[s,o]of Object.entries(e))n.has(s)||(i[s]=o);let r={...i,...t};return delete r.args,r}function CP(e,t){let n=Pr(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function ca(e){return{type:re(e,"filterType"),tag:re(e,"filterTag"),priority:re(e,"filterPriority"),deadlineBefore:re(e,"filterDeadlineBefore"),deadlineAfter:re(e,"filterDeadlineAfter"),updatedAfter:re(e,"filterUpdatedAfter"),updatedBefore:re(e,"filterUpdatedBefore"),createdAfter:re(e,"filterCreatedAfter"),createdBefore:re(e,"filterCreatedBefore"),ids:To(e.ids),assignee:re(e,"filterAssignee"),assigneeFilter:re(e,"filterAssigneeFilter")??re(e,"filterAssignee_filter"),parent:re(e,"filterParent"),sprint:re(e,"filterSprint"),release:re(e,"filterRelease"),limit:re(e,"limit"),offset:re(e,"offset")}}function aa(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return ua(e)}function Dr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function IP(e){let t=aa(e.kind),n=aa(e.exemptIsolate),i=aa(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Dr(e.maxDepth),limit:Dr(e.limit),after:O(e,"after"),direction:O(e,"direction"),maxPaths:Dr(e.maxPaths),sample:Dr(e.sample),...n===void 0?{}:{exemptIsolate:n},...i===void 0?{}:{exemptIsolateType:i},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function up(e){let t=f_(e);return e.ids!==void 0&&(t.ids=To(e.ids)),t}function xP(e){return{status:O(e,"filterStatus"),list:gn(e.list)?up(e.list):ca(e),reason:O(e,"reason"),resolution:O(e,"resolution"),expectedResult:O(e,"expectedResult")??O(e,"expected_result")??O(e,"expected"),actualResult:O(e,"actualResult")??O(e,"actual_result")??O(e,"actual"),validateClose:O(e,"validateClose")??O(e,"validate_close"),author:O(e,"author"),message:O(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var $b=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function ap(e){let t={};for(let[n,i]of Object.entries(e))$b.has(n)||(t[n]=i);return mp(t)}function mp(e){let t=lp(e,"update-many");for(let n of hr)for(let i of n.keys){let r=t[i];typeof r=="number"&&Number.isFinite(r)&&(t[i]=String(r))}return p_(t)}function RP(e){if(gn(e.list)||gn(e.update)){let t=gn(e.update)?e.update:ap(e),n=Pr(e,mp(t));return{status:re(e,"filterStatus"),list:gn(e.list)?up(e.list):ca(e),update:_l(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:re(e,"filterStatus"),list:ca(e),update:Pr(e,ap(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:O(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}import{createHash as pp}from"node:crypto";import ri from"node:fs/promises";import si 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]="fd8c4c35-98bb-5f3b-927d-8696125af703")}catch{}})();function Fe(e,t){throw new p(e,m.USAGE,t)}var Ub="2026-07-15T06:22:12.276Z",jb=Date.parse(Ub),Gb=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],_p=e=>typeof e=="string"?e:"",fp=e=>{let t=e??{},n=_p(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(_p(t.ts))>=jb);return Gb[i][r]};function gp(e,t,n=20,i=new Set,r=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[_,f]of t.split(/\r?\n/).entries()){let g;try{g=JSON.parse(f)}catch{continue}d+=1;let h=fp(g);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&i.has(`${e}:${_+1}`)){u+=1;continue}a[h]+=1,r&&h==="actionable_unknown"&&o.push({item_id:e,line:_+1}),s.length<c&&s.push({item_id:e,line:_+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var jP=(e,t,n=20,i=new Set)=>gp(e,t,n,i);function hp(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let s=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var oi=async(e,t=20,n=!1)=>{let i=si.join(e,"history"),r;try{r=(await ri.readdir(i)).filter(v=>v.endsWith(".jsonl")).sort((v,w)=>v.localeCompare(w))}catch{r=[]}let s=new Set,o=[],a=[],c=0,d=0,l=0,u=0,_=0,f=0,g="_workspace.jsonl",h=new Set;if(r.includes(g))try{h=hp(await ri.readFile(si.join(i,g),"utf8"))}catch{h=new Set}for(let v of r){let w;try{w=await ri.readFile(si.join(i,v),"utf8")}catch{continue}let S=v.slice(0,-6),E=gp(S,w,t-o.length,h,n);c+=1,d+=E.checked_events,l+=E.unknown_event_count,u+=E.legacy_unknown_event_count,_+=E.actionable_unknown_event_count,f+=E.acknowledged_actionable_event_count,E.unknown_event_count>0&&s.add(S),o.push(...E.samples),n&&a.push(...E.actionable_events)}let y=u+_;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:_,acknowledged_actionable_event_count:f,affected_item_ids:[...s].sort((v,w)=>v.localeCompare(w)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};function qb(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function Kb(e){try{return hp(await ri.readFile(si.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function zb(e){return(e.item_id===qn||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Wb(e,t,n){let i=n[e.line-1]??"",r;try{r=JSON.parse(i)}catch{Fe(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return fp(r)!=="actionable_unknown"&&Fe(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:pp("sha256").update(i).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function yp(e,t,n){let i=t.events??[],r=+(t.all_actionable===!0)+ +(i.length>0);r===0&&Fe("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),r>1&&Fe("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Fe("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=qb(t.all_actionable===!0?(await oi(e,0,!0)).actionable_events:i),o=await Kb(e),a=new Map;for(let _ of s)if(zb(_)||Fe(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(_.item_id))try{a.set(_.item_id,(await ri.readFile(si.join(e,"history",`${_.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Fe(`Unknown-author acknowledgment target ${_.item_id}:${_.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(_=>Wb(_,o,a.get(_.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=pp("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:_})=>_==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function GP(e,t,n=50){return(await yp(e,t,n)).plan}function Bb(e,t){let n=e.length>0;return n&&t&&Fe("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Fe("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:Vb(e),all_actionable:t}}function Vb(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),s=i===qn||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!s||!Number.isSafeInteger(r)||r<1)&&Fe(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function qP(e,t){let n=Bb(ua(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Hb(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:O(t,"planFingerprint")??O(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:O(t,"attributedAuthor")??O(t,"attributed_author")??void 0,reviewer:O(t,"reviewer"),reason:O(t,"reason")})}async function Hb(e,t){let n=t.reviewer?.trim()??"",i=t.attributed_author?.trim()??"",r=t.reason?.trim()??"",s=await yp(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:m.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&Fe("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Fe("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==s.plan.plan_fingerprint)throw new p("Author acknowledgment selection changed after preview; no history was mutated.",m.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=s.completeCoordinates.filter(({disposition:u})=>s.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:_})=>({item_id:u,line:_}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:m.NO_EFFECT,plan:s.plan};let c=await I(e),d=await an({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:i}},message:r,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),l=s.plan.actionable_count>0&&s.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:s.plan,history_path:d.historyPath}}import{createHash as Yb}from"node:crypto";import Fr 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]="e5ba549f-1965-5c5e-98b3-bd0903210032")}catch{}})();var Xb="2026-08-09T16:15:18.000Z",wp=Symbol("pre-durable-disposition-eligible");function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ma(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 vp(e){return lt(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 bp(e,t){if(typeof e!="string")return!1;let n=Fr.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!Fr.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(Fr.posix.basename(n)===`${t}.toon`||Fr.posix.basename(n)===`${t}.md`)}function Jb(e,t){return typeof e.receipt_id=="string"&&Jn(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&bp(e.item_path,t)}function kp(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,s=Array.isArray(r)?new Set(r.flatMap(o=>vp(o)?[o.field]:[])):new Set;return ma(t)&&ma(n)&&ma(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(vp)&&s.size===r.length&&t.length===s.size&&t.every(o=>s.has(o))}function Qb(e,t){return Jb(e,t)&&kp(e)}function Zb(e,t){return typeof e.receipt_id=="string"&&Jn(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&&bp(e.item_path,t)&&kp(e)}function ek(e){return e[wp]===!0}function Sp(e,t){if(!lt(e)||!lt(e.context))return[];let n=e.context.merge;return!lt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!lt(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:Qb(i,t),[wp]:Zb(i,t),...typeof e.ts=="string"&&yo(e.ts)?{eventTimestamp:e.ts}:{}}])}function Ep(e,t,n){if(!lt(e)||e.op!=="merge_reconcile")return[];if(!lt(e.context)||!lt(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!lt(r)||typeof r.receipt_id!="string"||!Jn(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"||!yo(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 Tp(e,t,n=[]){let i=new Map;for(let o of n){let a=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;i.set(a,Math.max(i.get(a)??0,o.auditHistoryLine))}let r=o=>ek(o)&&o.eventTimestamp!==void 0&&qi(o.eventTimestamp,Xb)<0&&(i.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!r(o)).map(o=>({item_id:o.itemId,history_line:o.line,...Jn(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:Yb("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77ccea6e-a118-53df-94b7-a740bb3d7681")}catch{}})();function $r(e,t,n=25){let i=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,a)=>o.localeCompare(a)),r=new Set(i),s=t.filter(o=>{let a=tn(o.status,e);return a!==void 0&&r.has(a)}).map(o=>o.id).sort((o,a)=>o.localeCompare(a));return{roleless_status_count:i.length,roleless_statuses:i.slice(0,n),roleless_statuses_truncated:i.length>n,affected_item_count:s.length,affected_item_ids:s.slice(0,n),affected_item_ids_truncated:s.length>n}}function Ur(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import ut from"node:fs/promises";import Ae from"node:path";import ai from"node:fs/promises";import jr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="84aca8e9-b9a8-59dd-8e11-aa9f67184ec4")}catch{}})();function tk(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:i,owner:r,created_at:s,ttl_seconds:o}=n;return typeof i!="string"||typeof r!="string"||typeof s!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:i,owner:r,created_at:s,ttl_seconds:o}}function Ap(e,t,n){let i=tk(t);if(i===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let r=Date.parse(i.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-r,o=Math.floor(s/1e3),a=s>i.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function Cp(e,t){let n=t??Date.now(),i=jr.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await ai.readdir(i)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(W(o))return r;throw o}for(let o of s){let a;try{a=await ai.readFile(jr.join(i,o),"utf8")}catch(d){if(W(d))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c}=Ap(o,a,n);c==="active"?r.active_lock_count+=1:c==="expired"?r.stale_lock_count+=1:r.unparseable_lock_count+=1}return r}async function Ip(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=jr.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await ai.readdir(s)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(W(c))return o;throw c}for(let c of a){o.scanned+=1;let d=jr.join(s,c),l=`locks/${c}`;if(i?.onRead){let f=await i.onRead(d);o.warnings.push(...f)}let u;try{u=await ai.readFile(d,"utf8")}catch(f){if(W(f)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(l),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=Ap(c,u,r);if(_.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(l),o.entries.push(_.entry);continue}if(_.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(l),o.entries.push(_.entry);continue}if(_.detail==="active"){o.retained.push(l),o.entries.push(_.entry);continue}if(!n){try{await ai.unlink(d)}catch(f){if(!W(f)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(l),o.entries.push(_.entry);continue}}if(i?.onWrite){let f=await i.onWrite(d);o.warnings.push(...f)}}o.removed.push(l),o.entries.push(_.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="836da277-15e2-5b29-9b18-5b3227a8d247")}catch{}})();var nk=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function _a(e){if(typeof e!="string")return;let t=e.trim();for(let n of nk)if(t===n.code||t.startsWith(`${n.code}:`))return n}function pa(e){let t={};for(let n of e){let i=_a(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function xp(e){return Object.values(pa(e))}import{execFile as ik}from"node:child_process";import{realpath as rk}from"node:fs/promises";import Rp from"node:path";import{promisify as sk}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]="be96ba6f-f848-58bf-8a3b-b6e3d6ab4b7a")}catch{}})();var ok=sk(ik),ak=32*1024*1024,ck=1e4,dk=["search/eval-queries.json"];function fa(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function lk(e){return`'${e.replaceAll("'","'\\''")}'`}async function uk(e,t=rk){return t(e).catch(()=>Rp.resolve(e))}async function Gr(e){let t=await wt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await uk(e),i=fa(Rp.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=a_.map(s=>`${i}/${fa(s)}`);try{let{stdout:s}=await ok("git",["ls-files","-z","--",...r.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:ak,windowsHide:!0,timeout:ck}),o=new Set(dk.map(d=>`${i}/${d}`)),a=[...new Set(s.split("\0").filter(d=>d.length>0&&!o.has(fa(d))))].sort((d,l)=>d.localeCompare(l)),c=r.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>lk(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62ab21f2-2dc9-5007-a70b-f2dbb45b1f8e")}catch{}})();var mk=new Set(mu),Lp=25,hn=8,Nt=100,_k=Ae.join("runtime","telemetry","events.jsonl"),pk=Ae.join("runtime","telemetry","state.json"),fk=2500,gk=500,Np=gu-3,hk=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function ba(e,t=!1){return 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 ka(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function yn(e){return e.trim().toLowerCase()}function ya(e,t){let n=yn(e),i=yn(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Sa(e){try{return(await ut.stat(e)).isDirectory()}catch{return!1}}async function yk(e){let t=(await ut.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>ut.readdir(Ae.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>It.some(s=>r.name.endsWith(s))).map(r=>Ae.parse(r.name).name)))}async function vk(e,t,n,i){let r=await Me({path:e,scope:"project"}),s=t!=="_workspace"&&!i.has(t);if(!n.enabled&&!s)return{warnings:r,overThreshold:!1,classification:"live"};let o;try{o=await ut.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let a="live";if(s){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="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:a}}async function wk(e,t,n){let i=Ae.join(e,"history");if(!await Sa(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ut.readdir(i)).filter(u=>u.endsWith(".jsonl")).sort((u,_)=>u.localeCompare(_)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of r){let _=Ae.join(i,u),f=u.slice(0,-6),g=await vk(_,f,t,n);a.push(...g.warnings),g.classification==="tombstone"&&d.push(f),g.classification==="orphaned"&&l.push(f),g.overThreshold&&c.push(f)}return{count:r.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function va(e,t){return Ae.relative(e,t).replaceAll("\\","/")}async function Dp(e,t){let n=[...new Set(Object.values(t))].sort((r,s)=>r.localeCompare(s)),i=[];for(let r of n){let s=Ae.join(e,r),o=[];try{o=await ut.readdir(s)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&W(a))continue;continue}for(let a of o)It.some(c=>a.toLowerCase().endsWith(c))&&i.push(Ae.join(s,a))}return i.sort((r,s)=>va(e,r).localeCompare(va(e,s))),i}function bk(e){return!(typeof e=="object"&&e!==null&&"code"in e&&W(e))}async function kk(e,t,n){let i=await Dp(e,t),r=[],s=[],o=[],a=[],c=ht(M());for(let d of i){let l=va(e,d),u;try{u=await ut.readFile(d,"utf8")}catch{r.push(l);continue}let _=rn(u);if(_){s.push({path:l,..._});continue}try{let f=cr(u,{format:Kd(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:or(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:s,parseFailures:o,formatVersions:a}}async function Sk(e){let t=Ae.join(e,"history"),n=[],i=[],r=[],s=[],o=[],a=[];try{a=(await ut.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){bk(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await ut.readFile(Ae.join(t,c),"utf8")}catch{n.push(d);continue}let u=rn(l);if(u){i.push({id:d,...u});continue}l.split(/\r?\n/).forEach((_,f)=>{if(_.trim())try{let g=JSON.parse(_);s.push(...Sp(g,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Ep(g,d,f+1))}catch{r.push({id:d,line:f+1})}})}return{files:a,unreadable:n,conflictMarkers:i,invalidJson:r,mergeReceiptReferences:s,mergeReceiptDispositions:o}}function Mp(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}`)]}function Ek(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}async function Tk(e,t,n,i,r){let s=await kk(e,t,n),o=await Sk(e),a=ar(s.formatVersions),c=K(n),d=kr(r,b=>de(b,c),Se()),l=await Gr(e),u=await wt(e),_=u===null?null:await ln(u),f=await un(u??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),g=new Set(f.receipts.map(b=>b.id)),h=Tp(o.mergeReceiptReferences,g,o.mergeReceiptDispositions),y=h.missing,v=f.receipts.filter(b=>b.state==="pending"),{pendingDecisions:w,lossless:S}=mn(v),E=_?.status==="missing"&&_.missing_keys.length===5&&_.drifted_keys.length===0,T=[...s.unreadable.map(b=>`integrity_item_unreadable:${b}`),...s.conflictMarkers.map(b=>`integrity_item_conflict_marker:${b.path}:L${b.line}`),...s.parseFailures.map(b=>`integrity_item_parse_failed:${b}`),...o.unreadable.map(b=>`integrity_history_unreadable:${b}`),...o.conflictMarkers.map(b=>`integrity_history_conflict_marker:${b.id}:L${b.line}`),...o.invalidJson.map(b=>`integrity_history_invalid_json:${b.id}:L${b.line}`),...a.outdated.map(b=>`integrity_item_outdated_format_version:${b}`),...a.ahead.map(b=>`integrity_item_ahead_format_version:${b}`),...Mp(d),...l.tracked_path_count>0?[`tracked_runtime_cache_files:${l.tracked_path_count}`]:[],..._!==null&&_.status!=="ok"?[`merge_driver_configuration_${E?"missing":"drift"}:${_.missing_keys.length+_.drifted_keys.length}`]:[],...w.length>0?[`merge_decisions_unreviewed:${w.length}`]:[],...S.length>0?[`merge_receipts_pending:${S.length}`]:[],...Ek({invalidEvidenceCount:f.invalid_evidence_count,missingHistoryReferenceCount:y.length})],A=[...new Set(T)].sort((b,L)=>b.localeCompare(L)),k=A.filter(b=>!b.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:k.length===0?"ok":"warn",ok:k.length===0,details:{checked_item_files:s.paths.length,checked_history_streams:o.files.length,counts:{item_unreadable:s.unreadable.length,item_conflict_markers:s.conflictMarkers.length,item_parse_failures:s.parseFailures.length,history_unreadable:o.unreadable.length,history_conflict_markers:o.conflictMarkers.length,history_invalid_json:o.invalidJson.length,item_outdated_format_version:a.outdated.length,item_ahead_format_version:a.ahead.length,hierarchy_cycles:d.cycles.length,hierarchy_cardinality_violations:d.cardinality_violations.length,hierarchy_parent_divergences:d.divergences.length,tracked_runtime_cache_files:l.tracked_path_count,merge_driver_configuration:_===null||_.status==="ok"?0:_.missing_keys.length+_.drifted_keys.length,pending_merge_decisions:w.length,lossless_merge_receipts:S.length,invalid_merge_receipt_evidence:f.invalid_evidence_count,missing_merge_receipt_history_references:y.length,accepted_legacy_merge_receipt_references:h.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:h.acceptedDispositionCount},item_unreadable:s.unreadable,item_conflict_markers:s.conflictMarkers,item_parse_failures:s.parseFailures,item_outdated_format_version:a.outdated,item_ahead_format_version:a.ahead,hierarchy_integrity:{...d,relations:Qe(d.relations,hn)},history_unreadable:o.unreadable,history_conflict_markers:o.conflictMarkers,history_invalid_json:o.invalidJson,tracked_runtime_cache:{tracker_relative_root:l.tracker_relative_root,tracked_paths:l.tracked_paths,tracked_path_count:l.tracked_path_count,remediation_command:l.remediation_command},merge_driver_configuration:_===null?null:{..._,required:i},pending_merge_decision_items:[...new Set(w.map(b=>b.item_id))].sort((b,L)=>b.localeCompare(L)),lossless_merge_receipt_items:[...new Set(S.map(b=>b.item_id))].sort((b,L)=>b.localeCompare(L)),invalid_merge_receipt_evidence_details:f.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:f.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:y.slice(0,Nt),missing_merge_receipt_history_reference_details_truncated:y.length>Nt}},warnings:A,gitWorkspaceRoot:u,pendingMergeReceipts:v}}function Ak(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Ck(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:Ak(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Ik(e,t){let n=ne(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function xk(e){let n=ne(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Rk(e){return ne(e.reason)??ne(e.error)??ne(e.message)}function ga(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 Ok(e){let t=[],n=[],i=[];e.forEach((s,o)=>{let a=Ik(s.definition,o),c=xk(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:a,status:c});return}if(c==="failed"){i.push({layer:s.layer,name:s.name,id:a,status:c,reason:Rk(s.definition)});return}n.push({layer:s.layer,name:s.name,id:a,status:c})}),t.sort(ga),n.sort(ga),i.sort(ga);let r=[...i.map(s=>`extension_migration_failed:${s.layer}:${s.name}:${s.id}`),...n.map(s=>`extension_migration_pending:${s.layer}:${s.name}:${s.id}`)];return{summary:{applied:t,pending:n,failed:i,applied_count:t.length,pending_count:n.length,failed_count:i.length},warnings:r}}function Pp(e,t,n,i,r,s,o,a,c){let d=[...new Set(e)].sort((y,v)=>y.localeCompare(v)),l=[...new Set(d.map(y=>ka(y)))].sort((y,v)=>y.localeCompare(v)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,_=c.length>0,f=_?"partial":"full",g=[],h=y_(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&g.push(h),t>0&&g.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&g.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(i.failed_count>0||i.pending_count>0)&&g.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&g.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&g.push(`Unknown extension capabilities detected. Allowed capabilities: ${Td.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&g.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&g.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),_?g.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&&g.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),g.length===0&&g.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:s,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:_,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:g}}async function Lk(e,t,n){let i=await w_(He(e)),r=await Hi({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=r.loaded.map(k=>Ck(k)),o=await op(r.loaded,He(e)),a=await Yi({...r,loaded:r.loaded}),[c,d]=await Promise.all([Ho(r.roots.project),Ho(r.roots.global)]);await v_(e,a.registrations.migrations);let l=Ok(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.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}}},_=new Set(c.state.entries.map(k=>yn(k.name))),f=new Set(d.state.entries.map(k=>yn(k.name))),g=[...new Map(r.loaded.filter(k=>!(k.layer==="project"?_:f).has(yn(k.name))).map(k=>[`${k.layer}:${k.name}`,{layer:k.layer,name:k.name,directory:k.directory}])).values()].sort((k,b)=>{let L=`${k.layer}:${k.name}`,q=`${b.layer}:${b.name}`;return L.localeCompare(q)}),h=g.map(k=>`${k.layer}:${k.name}`).sort((k,b)=>k.localeCompare(b)),y=g.filter(k=>ya(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,b)=>k.localeCompare(b)),v=g.filter(k=>!ya(k.name,k.directory)).map(k=>`${k.layer}:${k.name}`).sort((k,b)=>k.localeCompare(b)),w=v.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${v.length}`]:[],S=[...i.warnings,...r.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...w,...o.warnings],E=Yo(S),T=Xo(),A=Pp(S,r.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,y,v);return{check:{name:"extensions",status:S.length===0?"ok":"warn",ok:S.length===0,details:{...r,loaded:s,warnings:S,activation:u,author_manifest:i,triage:A,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:T,capability_guidance:E,host_version_census:o}},warnings:S}}function Nk(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Qe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Dk(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function qr(e,t){let n=Qe(e,t);return{...n,sample:n.sample.map(i=>Dk(i))}}function z(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(i=>typeof i=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function Mk(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var Pk={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:z(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:z(e.missing_required,t),missing_optional:z(e.missing_optional,t),missing:z(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:z(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:qr(e.discovered,t),effective:qr(e.effective,t),loaded:qr(e.loaded,t),failed:Qe(e.failed,t),warnings:z(e.warnings,t),activation:{failed:Qe(n.failed,t),warnings:z(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:Mk(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Qe(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:z(n.affected_item_ids,t),samples:Qe(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:z(e.item_unreadable,t),item_conflict_markers:Qe(e.item_conflict_markers,t),item_parse_failures:z(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:z(n.tracked_paths,t)},history_unreadable:z(e.history_unreadable,t),history_conflict_markers:Qe(e.history_conflict_markers,t),history_invalid_json:Qe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:z(n.candidate_items,t),confirmed_items:z(n.confirmed_items,t),resolved_false_positive_items:z(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:z(e.drifted_items,t),merge_receipt_attributed_items:z(e.merge_receipt_attributed_items,t),missing_streams:z(e.missing_streams,t),unreadable_streams:z(e.unreadable_streams,t),hash_mismatches:z(e.hash_mismatches,t),chain_mismatches:z(e.chain_mismatches,t),version_skews:z(e.version_skews,t),workspace_state_mismatches:z(e.workspace_state_mismatches,t),workspace_state_missing:z(e.workspace_state_missing,t),workspace_state_unreadable:z(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:z(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:z(e.stale_items_after,t),skipped:e.skipped})};function Fp(e,t){let n=Pk[e.name];return n?n(e.details,t):e.details}function Fk(e){let t=z(e.warnings,hn);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Fp(n,hn)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:hn},generated_at:e.generated_at}}function Op(e){return e.details.skipped===!0}function $k(e){let t=z(e.warnings,hn),n=e.checks.filter(Op).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!Op(i)).map(i=>({name:i.name,status:i.status,ok:i.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(i=>t.sample.includes(i.warning)||e.failed_because.includes(i.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:hn,omitted_checks:n},generated_at:e.generated_at}}function wa(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Nk(e,Lp);return{values:n.values,truncated:n.truncated,total:e.length}}function Kr(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Uk(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return mk.has(e)?e:null}function zr(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 $p(e){let t=0,n=0,i=0,r=0,s=0;for(let o of e.split(`
@@ -26,4 +26,4 @@ ${t}`;return JN.some(i=>i.test(n))}function Iv(e){let t=Ni(e);return/(?:^|\s)(?:
26
26
  `)}async function Nn(e,t){let n=Eo(e,t),i=await ee(n);return i?sw(i,n):null}async function vM(e){let t=So(e);return await Z(t)?(await On.readdir(t,{withFileTypes:!0})).filter(i=>i.isFile()&&i.name.endsWith(".json")).map(i=>Di.join(t,i.name)).sort((i,r)=>r.localeCompare(i)):[]}function wM(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function bM(e){if(process.platform==="linux")try{let t=await On.readFile(`/proc/${e}/status`,"utf8");return wM(t)}catch{return}}function kM(e){let t=e.lastIndexOf(")");if(t<0)return{};let i=e.slice(t+2).trim().split(/\s+/),r=Number.parseInt(i[11],10),s=Number.parseInt(i[12],10);return!Number.isFinite(r)||!Number.isFinite(s)?{}:{cpu_user_seconds:r/Xv,cpu_system_seconds:s/Xv}}async function SM(e){if(process.platform!=="linux")return{};try{let t=await On.readFile(`/proc/${e}/stat`,"utf8");return kM(t)}catch{return{}}}async function od(e){let t=e.child_pid??e.worker_pid;if(!Ln(t))return;let n=await bM(t),i=await SM(t),r=e.started_at?Date.parse(e.started_at):Number.NaN,s=Number.isFinite(r)?Math.max(0,(iw()-r)/1e3):void 0;return{recorded_at:R(),rss_bytes:n,cpu_user_seconds:i.cpu_user_seconds,cpu_system_seconds:i.cpu_system_seconds,uptime_seconds:s}}function sd(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function EM(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:sd(a.passed),failed:sd(a.failed),skipped:sd(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let i=Array.isArray(n.run_results)?n.run_results:[],r=0,s=0,o=0;for(let a of i){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){r+=1;continue}if(c==="failed"){s+=1;continue}o+=1}return{summary:{passed:r,failed:s,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function TM(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:R(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let i=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!i)return null;let r=Number.parseInt(i[1],10),s=Number.parseInt(i[2],10),o=i[4]?Number.parseInt(i[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:r,linked_test_total:s,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:R(),phase:i[3]?.toLowerCase()==="end"?"finished":"running"}}function AM(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function ad(e,t){if(t<=0)return[];let n=AM(e);return n.length<=t?n:n.slice(n.length-t)}async function ow(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let r=Di.resolve(e,t);if(await Z(r))return r}let n=Di.resolve(e,"dist","cli.js");if(await Z(n))return n;let i=process.argv[1]?.trim();if(i&&i.length>0){let r=Di.resolve(e,i);if(await Z(r))return r}throw new p("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",m.GENERIC_FAILURE)}async function Mi(e,t){if(!tw.has(t.status)||Ln(t.worker_pid)||t.finished_at)return t;let i={...t,status:"failed",finished_at:R(),error:t.error??"Background test run worker exited before writing terminal status."};return await nt(e,i),i}async function dd(e){await yM(e.pmRoot);let t=rw(e.commandArgs);if(t.length===0)throw new p("Background test run requires command arguments.",m.USAGE);let n=hM(e.kind,t,e.pmRoot),i=await ud(e.pmRoot,{});for(let l of i){let u=await Mi(e.pmRoot,l);if(u.fingerprint===n&&!(!tw.has(u.status)||!Ln(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let r=gM(),s=R(),o=Hd(e.pmRoot,r),a=Yd(e.pmRoot,r),c=Jd(e.pmRoot,r);await On.writeFile(o,"","utf8"),await On.writeFile(a,"","utf8");let d={id:r,kind:e.kind,status:"queued",created_at:s,updated_at:s,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:fM(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:s}};return await nt(e.pmRoot,d),{started:!0,run:d}}async function ld(e){let t=await Nn(e.pmRoot,e.runId);if(!t)throw new p(`Background test run ${e.runId} not found`,m.NOT_FOUND);if(cd.has(t.status))throw new p(`Background test run ${t.id} is already terminal (${t.status}).`,m.CONFLICT);let n=await ow(process.cwd()),i=[];e.noExtensions===!0&&i.push("--no-extensions"),i.push("--path",t.pm_root,"test-runs-worker",t.id);let r={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},s=ew(process.execPath,[n,...i],{cwd:process.cwd(),env:r,detached:!0,stdio:"ignore",windowsHide:!0});s.unref();let o={...t,status:"queued",worker_pid:s.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:R()}};return await nt(e.pmRoot,o),o}async function Jv(e,t,n){await e,await On.appendFile(t,n,"utf8")}function aw(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function CM(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function IM(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function xM(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await nt(e,t)}catch{}})},async flush(){await n}}}function Qv(e,t){try{e.kill(t)}catch{}}async function RM(e,t,n,i){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=R(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:R()},i(),Qv(t,"SIGTERM"),setTimeout(()=>Qv(t,"SIGKILL"),aw("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",_M)).unref?.()}function OM(e,t,n){return{phase:n,message:e,heartbeat_at:R(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function LM(e,t,n,i){return{phase:i,message:e,heartbeat_at:R(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function Zv(e,t,n){let i=TM(t);if(!i)return!1;let r=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=i.item_id?OM(t,i,r):LM(t,e,i,r),i.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function NM(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function DM(e,t){return t?"stopped":e.exit_code===0&&(e.summary?.failed??0)===0&&e.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function MM(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:R(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function PM(e,t,n){if(t!==null){await Ve(e.result_path,`${JSON.stringify(t,null,2)}
27
27
  `);return}await Ve(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:ad(n,nw)},null,2)}
28
28
  `)}async function cw(e,t,n=!1){let i=await Nn(e,t);if(!i)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let r={...i,status:"running",started_at:i.started_at??R(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:R()}},s=await ow(process.cwd()),o=CM(r);await nt(e,r);let a=IM(r,n),c=ew(process.execPath,[s,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});r.child_pid=c.pid;let d=xM(e,r),l=d.schedule,u=Promise.resolve(),_=Promise.resolve(),f="",g="",h={stopRequested:!1},y=()=>{RM(r,c,h,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let v=setInterval(()=>{(async()=>(r.resource=await od(r),r.progress.heartbeat_at=R(),l()))()},aw("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",mM));v.unref?.(),c.stdout?.on("data",k=>{let b=k.toString("utf8");f+=b,u=Jv(u,r.stdout_path,b)}),c.stderr?.on("data",k=>{let b=k.toString("utf8");_=Jv(_,r.stderr_path,b),g+=b;let L=g.split(/\r?\n/);g=L.pop();let q=!1;for(let F of L){let C=F.trimEnd();C.length>0&&Zv(r,C,h.stopRequested)&&(q=!0)}q&&l()});let w=null,S=null;try{({code:w,signal:S}=await new Promise(k=>{c.on("close",(b,L)=>{k({code:b,signal:L})})}))}finally{clearInterval(v),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await _;let E=g.trimEnd();E.length>0&&Zv(r,E,h.stopRequested)&&l(),g="";let T=NM(f),A=EM(r.kind,T);return r.summary=A.summary,r.exit_code=typeof w=="number"?w:void 0,r.signal=S??void 0,r.finished_at=R(),r.status=DM(r,h.stopRequested),r.progress=MM(r,h.stopRequested),r.resource=await od(r),await PM(r,T,f),await nt(e,r),await d.flush(),r}async function ud(e,t){let n=await vM(e),i=[];for(let c of n){let d=await ee(c);if(!d)continue;let l=await sw(d,c);i.push(l)}let r=[];for(let c of i)r.push(await Mi(e,c));let o=(t.status?r.filter(c=>c.status===t.status):r).sort((c,d)=>{let l=Date.parse(d.updated_at)-Date.parse(c.updated_at);return Number.isFinite(l)&&l!==0?l:d.id.localeCompare(c.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?o:o.slice(0,a)}async function dw(e,t){let n=await Nn(e,t);if(!n)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let i=await Mi(e,n),r=Ln(i.worker_pid),s=Ln(i.child_pid);i.status==="running"&&!s&&!i.finished_at&&!r&&(i.status="failed",i.finished_at=R(),i.error=i.error??"Background run process exited unexpectedly.",await nt(e,i)),i.status==="running"&&(i.resource=await od(i),await nt(e,i));let o=i.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,iw()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:pM,u=i.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:i,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:r,child_alive:s}}}function FM(e,t){let n=t?"SIGKILL":"SIGTERM";if(!Ln(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function $M(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:R(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function lw(e,t,n=!1){let i=await Nn(e,t);if(!i)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let r=await Mi(e,i);if(cd.has(r.status))return{run:r,signal_sent:"none"};let s=FM(r,n);return s==="none"&&(r.status="stopped",r.finished_at=r.finished_at??R()),r.stop_requested_at=R(),r.progress=$M(r,s),await nt(e,r),{run:r,signal_sent:s}}async function uw(e,t,n,i=!1){let r=await Nn(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let s=await Mi(e,r);if(!cd.has(s.status))throw new p(`Background test run ${t} is not terminal and cannot be resumed.`,m.CONFLICT);let o=await dd({pmRoot:s.pm_root,globalPmRoot:s.global_pm_root,kind:s.kind,commandArgs:s.command_args,requestedBy:n,targetId:s.target_id,statusFilter:s.status_filter,resumedFrom:s.id,resumedBy:n,attempt:s.attempt+1});if(!o.started)return o.run;let a=await ld({pmRoot:e,runId:o.run.id,noExtensions:i}),c={...s,resumed_by:a.id};return await nt(e,c),a}async function mw(e,t,n,i){let r=await Nn(e,t);if(!r)throw new p(`Background test run ${t} not found`,m.NOT_FOUND);let s=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):nw,o=n==="stdout"||n==="both"?await ee(r.stdout_path)??"":"",a=n==="stderr"||n==="both"?await ee(r.stderr_path)??"":"";return{run:r,stream:n,tail:s,stdout:n==="stdout"||n==="both"?ad(o,s):[],stderr:n==="stderr"||n==="both"?ad(a,s):[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7f8a7ea-3ec2-521b-ad52-45b655208f06")}catch{}})();var jM=["queued","running","passed","failed","stopped","canceled"],GM=["stdout","stderr","both"];function qM(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(jM.includes(t))return t;throw new p(`Invalid --status value "${e}"`,m.USAGE)}function KM(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(GM.includes(t))return t;throw new p(`Invalid --stream value "${e}"`,m.USAGE)}function zM(){try{let e=UM.userInfo().username.trim();if(e.length>0)return e}catch{}}function _w(e,t){let n=[e,kl(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,zM()];for(let i of n){if(typeof i!="string")continue;let r=i.trim();if(r.length>0)return r}return"unknown"}async function Vt(e){await P(e)}async function pV(e,t){let n=x(process.cwd(),t.path),i=Ye(process.cwd());await Vt(n);let r=await I(n),s=_w(e.author,r.author_default),o=await dd({pmRoot:n,globalPmRoot:i,kind:e.kind,commandArgs:e.commandArgs,requestedBy:s,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await ld({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function fV(e,t){let n=x(process.cwd(),t.path);await Vt(n);let i=qM(e.status),r=zn(e.limit,"limit"),s=await ud(n,{status:i,limit:r});return{runs:s,count:s.length,filters:{status:i,limit:r}}}async function gV(e,t){let n=x(process.cwd(),t.path);await Vt(n);let i=await dw(n,e);return{run:i.run,health:i.health}}async function hV(e,t,n){let i=x(process.cwd(),n.path);await Vt(i);let r=KM(t.stream),s=zn(t.tail,"tail"),o=await mw(i,e,r,s);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function yV(e,t,n){let i=x(process.cwd(),n.path);await Vt(i);let r=await lw(i,e,t.force===!0);return{run:r.run,signal_sent:r.signal_sent}}async function vV(e,t,n){let i=x(process.cwd(),n.path);await Vt(i);let r=await I(i),s=_w(t.author,r.author_default),o=await uw(i,e,s,t.noExtensions===!0);return{resumed_from:e,run:o}}async function wV(e,t){let n=x(process.cwd(),t.path);await Vt(n);let i=await cw(n,e,t.noExtensions===!0);return{id:i.id,status:i.status,exit_code:i.exit_code}}export{N as a,Re as b,Je as c,_n as d,M_ as e,F_ as f,ct as g,Zn as h,nb as i,ea as j,ta as k,G_ as l,fn as m,ti as n,ia as o,bb as p,V_ as q,ni as r,ra as s,Or as t,sa as u,Y_ as v,X_ as w,J_ as x,ii as y,Nr as z,Z_ as A,ep as B,tp as C,np as D,op as E,da as F,O as G,re as H,yP as I,gn as J,la as K,vP as L,wP as M,lp as N,bP as O,kP as P,SP as Q,Fb as R,EP as S,TP as T,ua as U,AP as V,CP as W,ca as X,IP as Y,xP as Z,mp as _,RP as $,Ub as aa,fp as ba,jP as ca,oi as da,GP as ea,Bb as fa,Vb as ga,qP as ha,Hb as ia,Xb as ja,Qb as ka,Zb as la,ek as ma,Sp as na,Ep as oa,Tp as pa,$r as qa,Ur as ra,Bp as sa,i$ as ta,Yp as ua,Jp as va,Zp as wa,jS as xa,GS as ya,qS as za,KS as Aa,di as Ba,zS as Ca,mt as Da,WS as Ea,BS as Fa,VS as Ga,xa as Ha,Ra as Ia,HS as Ja,Wr as Ka,Br as La,ef as Ma,j$ as Na,sf as Oa,af as Pa,rU as Qa,sU as Ra,Ma as Sa,_i as Ta,pi as Ua,NE as Va,kn as Wa,gf as Xa,Ga as Ya,yf as Za,vf as _a,sT as $a,Aj as ab,hg as bb,hi as cb,wg as db,bg as eb,kg as fb,ic as gb,pA as hb,a1 as ib,S1 as jb,gA as kb,Ft as lb,E1 as mb,hA as nb,Cg as ob,T1 as pb,yi as qb,A1 as rb,Ig as sb,Rg as tb,SA as ub,sc as vb,F1 as wb,oc as xb,G1 as yb,AA as zb,Ng as Ab,ac as Bb,Dg as Cb,GA as Db,ls as Eb,Ds as Fb,us as Gb,qg as Hb,yG as Ib,nC as Jb,iC as Kb,Bg as Lb,lc as Mb,jt as Nb,gs as Ob,Ut as Pb,Hg as Qb,vi as Rb,wi as Sb,hs as Tb,ys as Ub,Gt as Vb,qt as Wb,En as Xb,vs as Yb,ws as Zb,bs as _b,Xg as $b,hC as ac,uc as bc,kc as cc,XI as dc,p0 as ec,g0 as fc,Ks as gc,eK as hc,Nh as ic,pK as jc,fK as kc,gK as lc,Ic as mc,Ph as nc,rx as oc,wK as pc,bK as qc,Fh as rc,kK as sc,SK as tc,Uh as uc,BK as vc,XK as wc,JK as xc,QK as yc,Vh as zc,pz as Ac,xx as Bc,Pc as Cc,Rx as Dc,Ox as Ec,Lx as Fc,fz as Gc,gz as Hc,xz as Ic,Rz as Jc,Oz as Kc,Bx as Lc,ry as Mc,Dz as Nc,Jx as Oc,In as Pc,Qx as Qc,$z as Rc,Uz as Sc,Fc as Tc,jz as Uc,Gz as Vc,qz as Wc,tR as Xc,Kz as Yc,zz as Zc,Wz as _c,Bz as $c,rR as ad,uy as bd,Hz as cd,ly as dd,py as ed,lR as fd,Ai as gd,fR as hd,gy as id,yR as jd,r2 as kd,I2 as ld,By as md,Vy as nd,BO as od,Hy as pd,X2 as qd,Yy as rd,J2 as sd,Q2 as td,Js as ud,dL as vd,sW as wd,qc as xd,oW as yd,Kc as zd,lL as Ad,Oi as Bd,Zy as Cd,ev as Dd,xW as Ed,NW as Fd,iv as Gd,BW as Hd,td as Id,RB as Jd,UN as Kd,ao as Ld,zN as Md,id as Nd,Bv as Od,VB as Pd,pV as Qd,fV as Rd,gV as Sd,hV as Td,yV as Ud,vV as Vd,wV as Wd};
29
- //# sourceMappingURL=chunk-XEV7BHH3.js.map
29
+ //# sourceMappingURL=chunk-WDF7PP4P.js.map
@@ -1,2 +1,2 @@
1
- import{$ as M,$n as y,O as p,Ph as B,Q as h,Ze as D,_ as L,_e as _,da as F,g as P,h as m,j as E,k as N,oa as I,pf as w,qf as S,rf as V,sf as A,tf as b,uf as v,xf as $}from"./chunk-33PER336.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]="69117358-9878-589b-8918-e71599e6c7df")}catch{}})();var f=Object.freeze({clock:"PM_CLOCK",tickMs:"PM_CLOCK_TICK_MS",seed:"PM_SEED"});function C(e,t,n,o){return new h(e,p.USAGE,{code:"invalid_reproducible_process_environment",reason:t,field:n,required:`${f.clock} and ${f.seed}; ${f.tickMs} is optional`,nextSteps:[`Set ${f.clock} to an ISO-8601 instant with Z or a numeric UTC offset and ${f.seed} to a non-empty reproducibility seed.`,`Optionally set ${f.tickMs} to a non-negative integer; it defaults to 1.`,"Unset all three variables to retain normal wall-clock and cryptographic-random behavior."],recovery:{recovery_mode:"compact",provided_fields:o,missing_required_fields:t==="incomplete"?[f.clock,f.seed].filter(i=>!o.includes(i)):void 0}})}function Q(e){let t=e[f.clock],n=e[f.tickMs],o=e[f.seed],i=[[f.clock,t],[f.tickMs,n],[f.seed,o]].filter(a=>a[1]!==void 0).map(([a])=>a);if(i.length===0)return;if(t===void 0||o===void 0)throw C("Reproducible process execution requires PM_CLOCK and PM_SEED together.","incomplete",t===void 0?f.clock:f.seed,i);if(o.trim().length===0)throw C(`${f.seed} must not be empty.`,"invalid_value",f.seed,i);if(!F(t))throw C(`${f.clock} must be a valid ISO-8601 instant with Z or a numeric UTC offset.`,"invalid_value",f.clock,i);let s=n===void 0?1:Number(n);if(n?.trim().length===0||!Number.isSafeInteger(s)||s<0)throw C(`${f.tickMs} must be a non-negative integer.`,"invalid_value",f.tickMs,i);return L({clock:t,seed:o,tickMs:s})}function ee(e){let t=Q(e);return t===void 0?n=>n():M(t)}async function Ue(e,t){return ee(e)(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]="e1db7644-e481-5049-a773-fcffa09f1779")}catch{}})();var R=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),z=new Map([["files","discover"],["item","complete"]]),te=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function G(e){let t=m(e?.trim().toLowerCase()??"");return R.has(t)||z.has(t)}function ne(e,t,n){let o=R.has(n)?t+1:void 0,i=b(e.slice(t+1));if(i===void 0)return o;let s=t+1+i,a=`${n} ${e[s]}`,r=m(a);return r===a?n==="item"&&e[s]==="complete"?s+1:o:G(r)?O(e,s,r):void 0}function O(e,t,n){if(["history","context","ctx","update","close","item"].includes(n))return ne(e,t,n);let o=z.get(n);if(o===void 0)return t+1;let i=e[t+1]?.toLowerCase()===o;return t+(i?2:1)}function oe(e){let t=new Map;for(let n of y(e))for(let o of[n.flag,n.short,...n.aliases??[]])o&&t.set(o,n);return t}function ie(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o==="--id"?(t.push({index:n,consumed:2,value:e[n+1]}),n+=1):o.startsWith("--id=")&&t.push({index:n,consumed:1,value:o.slice(5)})}return t}function se(e,t,n){if(e.indexOf("=")>=0||t===void 0||t.startsWith("-"))return!1;let i=n.get(e);return i!==void 0&&i.value_type!=="boolean"}function re(e,t,n,o,i){let s=0;for(let a=t;a<e.length;a+=1){let r=e[a];if(r==="--")break;if(r==="--id"){a+=1;continue}if(!r.startsWith("--id=")){if(!r.startsWith("-")){if(a<o)return!0;s+=1;continue}se(r,e[a+1],i)&&(a+=1)}}return s>(te.get(m(n))??0)}function W(e){let t=b(e),n=t===void 0?void 0:e[t]?.toLowerCase();if(n!=="context"&&n!=="ctx"&&!G(n))return{argv:[...e],changed:!1,conflict:!1};let o=O(e,t,n);if(o===void 0)return{argv:[...e],changed:!1,conflict:!1};let i=o>t+1?`${m(e.slice(t,o-1).join(" "))} ${e[o-1]}`:n,s=oe(i),a=ie(e),r=a[0];if(!r||!r.value?.trim())return{argv:[...e],changed:!1,conflict:!1};if(a.length>1||re(e,o,i,r.index,s))return{argv:[...e],changed:!1,conflict:!0,itemId:r.value};let c=[...e.slice(0,r.index),...e.slice(r.index+r.consumed)],l=b(c),u=O(c,l,n);return c.splice(u,0,r.value),{argv:c,changed:!0,conflict:!1,itemId:r.value}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ef3b254-0494-57bc-8bbf-8ee58eb7d152")}catch{}})();var ae=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]);function ce(e,t,n){let o=e[t];if(S.has(o))return n.booleanFlags.add(o),1;let i=o.indexOf("="),s=i>0?o.slice(0,i):o;if(!w.has(s))return 1;let a=i>0?o.slice(i+1):void 0,r=a===void 0&&A(s,e[t+1]),c=a??(r?e[t+1]:void 0);return s==="--author"?n.author=c??"":typeof c=="string"&&c.length>0&&(ae.has(s)?n.outputValues:n.pathValues).set(s,c),r?2:1}function le(e){let t={booleanFlags:new Set,outputValues:new Map,pathValues:new Map},n=0;for(;n<e.length&&e[n]!=="--";)n+=ce(e,n,t);return{path:t.pathValues.get("--pm-path")??t.pathValues.get("--path"),noExtensions:t.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(X(e)??""),noPager:t.booleanFlags.has("--no-pager"),json:t.booleanFlags.has("--json"),quiet:t.booleanFlags.has("--quiet"),lean:t.booleanFlags.has("--lean"),tokenAccounting:t.booleanFlags.has("--token-accounting"),...t.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...t.outputValues.get("--output-include")===void 0?{}:{outputInclude:t.outputValues.get("--output-include")},...t.outputValues.get("--output-limit")===void 0?{}:{outputLimit:t.outputValues.get("--output-limit")},...t.outputValues.get("--output-budget")===void 0?{}:{outputBudget:t.outputValues.get("--output-budget")},...t.outputValues.get("--output-format")==="toon"||t.outputValues.get("--output-format")==="json"?{outputFormat:t.outputValues.get("--output-format")}:{},...t.outputValues.get("--output-session")===void 0?{}:{outputSession:t.outputValues.get("--output-session")},...t.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:t.outputValues.get("--output-cursor")},...t.author===""?{authorMissingValue:!0}:t.author!==void 0?{author:t.author}:{}}}function j(e){let t=[],n=0;for(;n<e.length;){let o=e[n];if(o==="--")break;if(S.has(o)||o==="--profile"||o==="--id-only"||o==="--full-changed-fields"||o==="--explain"){n+=1;continue}if(w.has(o)){n+=A(o,e[n+1])?2:1;continue}if(V(o)){n+=1;continue}t.push(o),n+=1}return t}function ue(e){let t=j(e);if(t[0]?.trim().toLowerCase()==="help"){let s=[];for(let a=1;a<t.length;a+=1){let r=t[a];if(r.startsWith("-"))break;s.push(r.trim().toLowerCase())}return{requested:!0,commandPathTokens:s}}if(t.findIndex(s=>s==="--help"||s==="-h")<0)return{requested:!1,commandPathTokens:[]};let i=[];for(let s of t){if(s.startsWith("-"))break;i.push(s.trim().toLowerCase())}return{requested:!0,commandPathTokens:i}}function k(e){return b(e)}function de(e){return v(e)}function fe(e,t){return t.noPager?!0:process.stdout.isTTY===!0?!1:ue(e).requested}function rt(e){let t=["PAGER","MANPAGER","GIT_PAGER","LESS"],n=t.map(s=>process.env[s]),o=()=>{for(let[s,a]of t.entries()){let r=n[s];r===void 0?delete process.env[a]:process.env[a]=r}},i=le(e);return fe(e,i)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),o}var pe=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function me(e){let t=k(e);if(t===void 0||e[t]!=="extension")return[...e];let n=e[t+1];if(!n||n.startsWith("-"))return[...e];if(!pe.has(n))return[...e];if(e.includes("--help")||e.includes("-h"))return[...e];let o=`--${n}`;return e.includes(o)?[...e]:[...e.slice(0,t+1),o,...e.slice(t+2)]}var he=new Set(["pm","pm-cli"]);function ge(e,t){let n=k(e);if(n===void 0)return e;let o=e[n];return he.has(o.trim().toLowerCase())?(t.push({from:o,to:[],reason:"executable_alias",confidence:"high"}),[...e.slice(0,n),...e.slice(n+1)]):e}function be(e,t){let n=k(e);if(n!==void 0&&e[n]==="help"){let r=k(e.slice(n+1));n=r===void 0?void 0:n+1+r}if(n===void 0)return e;let o=e[n],i=N[o.trim().toLowerCase()];if(!i)return e;let s=i.split(" "),a=[...e.slice(0,n),...s,...e.slice(n+1)];return t.push({from:o,to:s,reason:"command_alias",confidence:"high"}),a}function x(e){return e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function U(e){return x(e).replace(/-/g,"")}function q(e,t,n){let o=e.get(t);if(o===void 0){e.set(t,n);return}o!==n&&e.set(t,null)}function ye(e){let t=[],n=o=>{typeof o=="string"&&o.startsWith("--")&&t.push(o)};n(e.flag);for(let o of e.aliases??[])n(o);return t}function we(e,t){let n=t??y(e),o=new Map,i=new Map,s=new Map,a=new Set;for(let r of n){let c=ye(r);if(c.length===0)continue;let l=`--${x(c[0])}`;for(let d of c)q(o,x(d),l),q(i,U(d),l);let u=U(l);s.has(l)||s.set(l,u),r.list===!0&&a.add(l)}return{canonicalByNormalized:o,canonicalByCompact:i,canonicalComparables:[...s.entries()].map(([r,c])=>({canonicalFlag:r,comparable:c})),listCanonicalFlags:a}}function K(e,t){let n=x(e),o=t.canonicalByNormalized.get(n);if(typeof o=="string")return{flag:o,reason:"flag_alias",confidence:"high"};let i=n.replace(/-/g,""),s=t.canonicalByCompact.get(i);if(typeof s=="string")return{flag:s,reason:"flag_alias",confidence:"high"};let a=i.length>=8?2:1,r=Number.POSITIVE_INFINITY,c,l=!1;for(let u of t.canonicalComparables){let d=I(i,u.comparable,a);if(d!==null){if(d<r){r=d,c=u.canonicalFlag,l=!1;continue}d===r&&c!==u.canonicalFlag&&(l=!0)}}return!c||l||!Number.isFinite(r)||r<=0?null:{flag:c,reason:"flag_typo",confidence:r>=2?"medium":"high"}}function at(e){let t=[`${e}s`];return e.endsWith("y")&&e.length>1&&t.push(`${e.slice(0,-1)}ies`),t}function Ie(e,t=!1){if(t||e.includes("://"))return null;let n=e.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!n)return null;let o=n[1],i=n[3];return i.length===0?null:{key:o,value:i}}function _e(e,t,n=!1){if(n||!e.startsWith("--"))return{tokens:[e]};let o=e.indexOf("="),i=o>=0?e.slice(0,o):e,s=o>=0?e.slice(o+1):void 0,a=K(i,t);if(!a)return{tokens:[e]};let r=s===void 0?a.flag:`${a.flag}=${s}`;return r===e?{tokens:[e]}:{tokens:[r],event:{from:e,to:[r],reason:a.reason,confidence:a.confidence}}}function ve(e){let t=new Set,n=!1;for(let o=0;o<e.length;o+=1){if(n){t.add(o),n=!1;continue}let i=e[o];n=i==="--path"||i==="--pm-path"}return t}function Ce(e){if(!e.startsWith("--"))return null;let t=e.indexOf("=");return t<0?{flag:e}:{flag:e.slice(0,t),inlineValue:e.slice(t+1)}}function ke(e,t,n){n.push(e[t]);let o=e[t+1];return typeof o=="string"&&o!=="--"?(n.push(o),t+2):t+1}function xe(e,t,n,o){if(n.inlineValue!==void 0)return{originalTokens:[e[t]],value:n.inlineValue,consumed:1};let i=[],s=t+1;for(;s<e.length&&e[s]!=="--"&&!e[s].startsWith("-")&&(i.length===0||o.has(n.flag));)i.push(e[s]),s+=1;let a=i.length===0?1:1+i.length;return{originalTokens:e.slice(t,t+a),value:i.length===0?void 0:i.join(","),consumed:a}}function Te(e,t,n,o){let i=e.get(n);if(i){i.values.push(o.value),i.occurrences+=1;return}e.set(n,{outputIndex:t.length,originalTokens:o.originalTokens,values:[o.value],occurrences:1}),t.push(null)}function Ee(e,t){let n=[],o=[];for(let[i,s]of e){if(!(s.occurrences>=2||t.has(i)&&s.originalTokens.length>2)){o.push({outputIndex:s.outputIndex,tokens:s.originalTokens});continue}let r=`${i}=${s.values.join(",")}`;o.push({outputIndex:s.outputIndex,tokens:[r]}),n.push({from:`${i} (x${s.occurrences})`,to:[r],reason:"list_merge",confidence:"high"})}return{events:n,splices:o}}function Se(e,t){t.sort((n,o)=>o.outputIndex-n.outputIndex);for(let n of t)e.splice(n.outputIndex,1,...n.tokens)}function Ae(e,t,n=new Set,o=new Set){if(t.size===0)return{argv:[...e],events:[]};let i=[],s=new Map,a=0;for(;a<e.length;){let l=e[a];if(l==="--"){i.push(...e.slice(a));break}if(n.has(l)){a=ke(e,a,i);continue}let u=Ce(l);if(!u||!t.has(u.flag)){i.push(l),a+=1;continue}let d=xe(e,a,u,o);if(d.value===void 0){i.push(l),a+=d.consumed;continue}Te(s,i,u.flag,{originalTokens:d.originalTokens,value:d.value}),a+=d.consumed}let{events:r,splices:c}=Ee(s,o);return Se(i,c),{argv:i,events:r}}var Y=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function Oe(e,t){if(e!=="test"||t.length<2)return!1;let n=t[t.length-1],o=t[t.length-2],i=Y.get(o);return i!==void 0&&i.has(n)}function Pe(e,t){return e==="search"||Oe(e,t)}function Ne(e,t,n){if(t!=="test")return e;let o=[],i=0;for(;i<e.length;){let s=e[i];if(s==="--")return o.push(...e.slice(i)),o;let a=Y.get(s),r=a?e[i+1]:void 0;if(!a||typeof r!="string"||!a.has(r)){o.push(s),i+=1;continue}let c=i+2;for(;c<e.length&&!e[c].startsWith("-");)c+=1;if(c-(i+2)!==1){o.push(s),i+=1;continue}let l=e[i+2],u=`${r}=${l}`;o.push(s,u),n.push({from:`${s} ${r} ${l}`,to:[s,u],reason:"bare_key_value",confidence:"high"}),i+=3}return o}function Le(e,t,n,o){let i=[],s=ve(e);for(let a=0;a<e.length;a+=1){let r=e[a];if(r==="--"){i.push(...e.slice(a));break}let c=s.has(a),l=i[i.length-1];if(r.startsWith("--")){let d=_e(r,t,c);i.push(...d.tokens),d.event&&o.push(d.event);continue}let u=Ie(r,c);if(u&&!(typeof l=="string"&&l.startsWith("-"))&&!Pe(n,i)){let d=K(u.key,t);if(d){let g=[d.flag,u.value];i.push(...g),o.push({from:r,to:g,reason:"bare_key_value",confidence:d.confidence});continue}}i.push(r)}return i}function Me(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--verify"){let o=e[t+1];if(o===void 0||o==="--")throw new h("history attest --verify requires a bundle file.",p.USAGE);e.splice(t,2,`--verify=${o}`)}else(w.has(n)||n==="--output"||n==="--hash-algorithm")&&(t+=1)}}function ct(e){let t=[],n=ge(e,t),o=me(n);(o.length!==n.length||o.some((T,J)=>T!==n[J]))&&t.push({from:n.join(" "),to:[...o],reason:"legacy_extension_action",confidence:"high"});let i=be(o,t),s=W(i);if(s.conflict)throw new h("Provide the item id either positionally or with --id, not both.",p.USAGE);s.changed&&t.push({from:`--id ${s.itemId}`,to:[s.itemId],reason:"item_id_alias",confidence:"high"});let a=de(s.argv),r=X(s.argv),c=m(r??a??""),l=we(r??a),u=Le(s.argv,l,c,t),d=Ne(u,c,t),g=Ae(d,l.listCanonicalFlags,w,a==="create"?new Set(["--tags"]):new Set);for(let T of g.events)t.push(T);return r==="history attest"&&Me(g.argv),{argv:g.argv,commandName:a,trace:t}}function X(e){let t=j(e),n=t[0]?.trim().toLowerCase(),o=t[1]?.trim().toLowerCase(),i=P(t);return i?i.canonical:(n==="extension"||n==="package"||n==="packages")&&typeof o=="string"&&o.length>0&&!o.startsWith("-")?`${n} ${o}`:n}function lt(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--type"){let o=e[t+1];if(typeof o=="string"&&o.trim().length>0)return o.trim();continue}if(n.startsWith("--type=")){let o=n.slice(7).trim();if(o.length>0)return o}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f7274c6-547e-5590-b7c9-a4d6418bf860")}catch{}})();function Z(e){return e.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function mt(e){if(!(!Array.isArray(e)||e.length===0))return v(e)}function Fe(e,t){let n=Z(t);if(!n)return;let o=y(e).find(i=>i.flag===n||i.aliases?.includes(n));return o?o.value_type==="boolean"?null:`<${o.value_name??"value"}>`:"<value>"}function ht(e,t,n){let o=[...e],i=o.indexOf("--"),s=i<0?o.length:i;for(let a of n){let r=Z(a);if(!r||o.slice(0,s).some(u=>u===r||u.startsWith(`${r}=`)))continue;let c=Fe(t,r),l=c?[r,c]:[r];o.splice(s,0,...l),s+=l.length}return o.length===e.length?void 0:$(o)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bd9a8d3b-bc6f-5309-a3fb-7e5f41ef9dab")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bdf3dec8-63d1-5ea6-a413-64be0ae8f69f")}catch{}})();function vt(e){return e instanceof h||e instanceof Error?e.message:"Unknown failure"}function De(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ve(e){let t=Math.trunc(e);return t>p.SUCCESS?t:p.GENERIC_FAILURE}function Ct(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function kt(e,t){if(e instanceof Error)return e;let n=new Error(t),o=De(e);return o!==void 0&&(n.exitCode=Ve(o)),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]="d22b586a-5c12-518e-b1ee-4baa0d04243b")}catch{}})();function At(e){if(e===void 0)return()=>{};let t=e.trim();if(t.length===0)throw new h("--author requires a non-empty value.",p.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});let n=D();_(t);let o=!1;return()=>{o||(o=!0,n===void 0?_(void 0):_(n))}}import{Command as $e}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8da6368-489f-579a-8a64-a9bb025f95e7")}catch{}})();function Lt(e){return new $e().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(e).showHelpAfterError(!1).allowExcessArguments(!1).allowUnknownOption(!1).configureOutput({writeOut:t=>{B(t)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the read-output encoding").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include the machine-readable row selector and TOON encoding contract").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="925e5fec-4cc0-5315-a331-03cb128893f0")}catch{}})();var Be={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function H(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" "),s=Be[o]?.indexOf(m(n));if(s!==void 0&&s>=0)return s;if(n===o)return 10;if(i.includes(o))return 11;if(i.some(c=>c.startsWith(o)))return 12;let a=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let c of i){let l=I(c,o,a);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?20+r:n.includes(o)?30:Number.POSITIVE_INFINITY}function Vt(e,t){return e.map(n=>({path:n,score:H(n,t)})).filter(n=>Number.isFinite(n.score)).sort((n,o)=>n.score!==o.score?n.score-o.score:n.path===o.path?0:n.path<o.path?-1:1).map(n=>n.path)}function $t(e,t,n){let o=new Set(t),i=E.filter(r=>r.lifecycle==="deprecated").slice().sort((r,c)=>c.alias.length-r.alias.length),s=[],a=e.flatMap(r=>{let c=i.find(u=>r===u.alias||r.startsWith(`${u.alias} `)),l=r;if(c){let u=r.slice(c.alias.length);if(!o.has(`${c.canonical}${u}`))return[];l=`${c.canonical_argv.join(" ")}${u}`}return n!==void 0&&H(r,n)<10&&s.push(l),[l]});return[...new Set(s.length>0?s:a)]}export{f as a,Q as b,ee as c,Ue as d,G as e,W as f,le as g,j as h,ue as i,k as j,de as k,rt as l,me as m,at as n,Ae as o,Ne as p,ct as q,lt as r,mt as s,Fe as t,ht as u,vt as v,De as w,Ve as x,Ct as y,kt as z,At as A,Lt as B,H as C,Vt as D,$t as E};
2
- //# sourceMappingURL=chunk-A2Q64TGR.js.map
1
+ import{$ as M,$n as y,O as p,Ph as B,Q as h,Ze as D,_ as L,_e as _,da as F,g as P,h as m,j as E,k as N,oa as I,pf as w,qf as S,rf as V,sf as A,tf as b,uf as v,xf as $}from"./chunk-J4DRE3WN.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]="69117358-9878-589b-8918-e71599e6c7df")}catch{}})();var f=Object.freeze({clock:"PM_CLOCK",tickMs:"PM_CLOCK_TICK_MS",seed:"PM_SEED"});function C(e,t,n,o){return new h(e,p.USAGE,{code:"invalid_reproducible_process_environment",reason:t,field:n,required:`${f.clock} and ${f.seed}; ${f.tickMs} is optional`,nextSteps:[`Set ${f.clock} to an ISO-8601 instant with Z or a numeric UTC offset and ${f.seed} to a non-empty reproducibility seed.`,`Optionally set ${f.tickMs} to a non-negative integer; it defaults to 1.`,"Unset all three variables to retain normal wall-clock and cryptographic-random behavior."],recovery:{recovery_mode:"compact",provided_fields:o,missing_required_fields:t==="incomplete"?[f.clock,f.seed].filter(i=>!o.includes(i)):void 0}})}function Q(e){let t=e[f.clock],n=e[f.tickMs],o=e[f.seed],i=[[f.clock,t],[f.tickMs,n],[f.seed,o]].filter(a=>a[1]!==void 0).map(([a])=>a);if(i.length===0)return;if(t===void 0||o===void 0)throw C("Reproducible process execution requires PM_CLOCK and PM_SEED together.","incomplete",t===void 0?f.clock:f.seed,i);if(o.trim().length===0)throw C(`${f.seed} must not be empty.`,"invalid_value",f.seed,i);if(!F(t))throw C(`${f.clock} must be a valid ISO-8601 instant with Z or a numeric UTC offset.`,"invalid_value",f.clock,i);let s=n===void 0?1:Number(n);if(n?.trim().length===0||!Number.isSafeInteger(s)||s<0)throw C(`${f.tickMs} must be a non-negative integer.`,"invalid_value",f.tickMs,i);return L({clock:t,seed:o,tickMs:s})}function ee(e){let t=Q(e);return t===void 0?n=>n():M(t)}async function Ue(e,t){return ee(e)(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]="e1db7644-e481-5049-a773-fcffa09f1779")}catch{}})();var R=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),z=new Map([["files","discover"],["item","complete"]]),te=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function G(e){let t=m(e?.trim().toLowerCase()??"");return R.has(t)||z.has(t)}function ne(e,t,n){let o=R.has(n)?t+1:void 0,i=b(e.slice(t+1));if(i===void 0)return o;let s=t+1+i,a=`${n} ${e[s]}`,r=m(a);return r===a?n==="item"&&e[s]==="complete"?s+1:o:G(r)?O(e,s,r):void 0}function O(e,t,n){if(["history","context","ctx","update","close","item"].includes(n))return ne(e,t,n);let o=z.get(n);if(o===void 0)return t+1;let i=e[t+1]?.toLowerCase()===o;return t+(i?2:1)}function oe(e){let t=new Map;for(let n of y(e))for(let o of[n.flag,n.short,...n.aliases??[]])o&&t.set(o,n);return t}function ie(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o==="--id"?(t.push({index:n,consumed:2,value:e[n+1]}),n+=1):o.startsWith("--id=")&&t.push({index:n,consumed:1,value:o.slice(5)})}return t}function se(e,t,n){if(e.indexOf("=")>=0||t===void 0||t.startsWith("-"))return!1;let i=n.get(e);return i!==void 0&&i.value_type!=="boolean"}function re(e,t,n,o,i){let s=0;for(let a=t;a<e.length;a+=1){let r=e[a];if(r==="--")break;if(r==="--id"){a+=1;continue}if(!r.startsWith("--id=")){if(!r.startsWith("-")){if(a<o)return!0;s+=1;continue}se(r,e[a+1],i)&&(a+=1)}}return s>(te.get(m(n))??0)}function W(e){let t=b(e),n=t===void 0?void 0:e[t]?.toLowerCase();if(n!=="context"&&n!=="ctx"&&!G(n))return{argv:[...e],changed:!1,conflict:!1};let o=O(e,t,n);if(o===void 0)return{argv:[...e],changed:!1,conflict:!1};let i=o>t+1?`${m(e.slice(t,o-1).join(" "))} ${e[o-1]}`:n,s=oe(i),a=ie(e),r=a[0];if(!r||!r.value?.trim())return{argv:[...e],changed:!1,conflict:!1};if(a.length>1||re(e,o,i,r.index,s))return{argv:[...e],changed:!1,conflict:!0,itemId:r.value};let c=[...e.slice(0,r.index),...e.slice(r.index+r.consumed)],l=b(c),u=O(c,l,n);return c.splice(u,0,r.value),{argv:c,changed:!0,conflict:!1,itemId:r.value}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ef3b254-0494-57bc-8bbf-8ee58eb7d152")}catch{}})();var ae=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]);function ce(e,t,n){let o=e[t];if(S.has(o))return n.booleanFlags.add(o),1;let i=o.indexOf("="),s=i>0?o.slice(0,i):o;if(!w.has(s))return 1;let a=i>0?o.slice(i+1):void 0,r=a===void 0&&A(s,e[t+1]),c=a??(r?e[t+1]:void 0);return s==="--author"?n.author=c??"":typeof c=="string"&&c.length>0&&(ae.has(s)?n.outputValues:n.pathValues).set(s,c),r?2:1}function le(e){let t={booleanFlags:new Set,outputValues:new Map,pathValues:new Map},n=0;for(;n<e.length&&e[n]!=="--";)n+=ce(e,n,t);return{path:t.pathValues.get("--pm-path")??t.pathValues.get("--path"),noExtensions:t.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(X(e)??""),noPager:t.booleanFlags.has("--no-pager"),json:t.booleanFlags.has("--json"),quiet:t.booleanFlags.has("--quiet"),lean:t.booleanFlags.has("--lean"),tokenAccounting:t.booleanFlags.has("--token-accounting"),...t.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...t.outputValues.get("--output-include")===void 0?{}:{outputInclude:t.outputValues.get("--output-include")},...t.outputValues.get("--output-limit")===void 0?{}:{outputLimit:t.outputValues.get("--output-limit")},...t.outputValues.get("--output-budget")===void 0?{}:{outputBudget:t.outputValues.get("--output-budget")},...t.outputValues.get("--output-format")==="toon"||t.outputValues.get("--output-format")==="json"?{outputFormat:t.outputValues.get("--output-format")}:{},...t.outputValues.get("--output-session")===void 0?{}:{outputSession:t.outputValues.get("--output-session")},...t.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:t.outputValues.get("--output-cursor")},...t.author===""?{authorMissingValue:!0}:t.author!==void 0?{author:t.author}:{}}}function j(e){let t=[],n=0;for(;n<e.length;){let o=e[n];if(o==="--")break;if(S.has(o)||o==="--profile"||o==="--id-only"||o==="--full-changed-fields"||o==="--explain"){n+=1;continue}if(w.has(o)){n+=A(o,e[n+1])?2:1;continue}if(V(o)){n+=1;continue}t.push(o),n+=1}return t}function ue(e){let t=j(e);if(t[0]?.trim().toLowerCase()==="help"){let s=[];for(let a=1;a<t.length;a+=1){let r=t[a];if(r.startsWith("-"))break;s.push(r.trim().toLowerCase())}return{requested:!0,commandPathTokens:s}}if(t.findIndex(s=>s==="--help"||s==="-h")<0)return{requested:!1,commandPathTokens:[]};let i=[];for(let s of t){if(s.startsWith("-"))break;i.push(s.trim().toLowerCase())}return{requested:!0,commandPathTokens:i}}function k(e){return b(e)}function de(e){return v(e)}function fe(e,t){return t.noPager?!0:process.stdout.isTTY===!0?!1:ue(e).requested}function rt(e){let t=["PAGER","MANPAGER","GIT_PAGER","LESS"],n=t.map(s=>process.env[s]),o=()=>{for(let[s,a]of t.entries()){let r=n[s];r===void 0?delete process.env[a]:process.env[a]=r}},i=le(e);return fe(e,i)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),o}var pe=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function me(e){let t=k(e);if(t===void 0||e[t]!=="extension")return[...e];let n=e[t+1];if(!n||n.startsWith("-"))return[...e];if(!pe.has(n))return[...e];if(e.includes("--help")||e.includes("-h"))return[...e];let o=`--${n}`;return e.includes(o)?[...e]:[...e.slice(0,t+1),o,...e.slice(t+2)]}var he=new Set(["pm","pm-cli"]);function ge(e,t){let n=k(e);if(n===void 0)return e;let o=e[n];return he.has(o.trim().toLowerCase())?(t.push({from:o,to:[],reason:"executable_alias",confidence:"high"}),[...e.slice(0,n),...e.slice(n+1)]):e}function be(e,t){let n=k(e);if(n!==void 0&&e[n]==="help"){let r=k(e.slice(n+1));n=r===void 0?void 0:n+1+r}if(n===void 0)return e;let o=e[n],i=N[o.trim().toLowerCase()];if(!i)return e;let s=i.split(" "),a=[...e.slice(0,n),...s,...e.slice(n+1)];return t.push({from:o,to:s,reason:"command_alias",confidence:"high"}),a}function x(e){return e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function U(e){return x(e).replace(/-/g,"")}function q(e,t,n){let o=e.get(t);if(o===void 0){e.set(t,n);return}o!==n&&e.set(t,null)}function ye(e){let t=[],n=o=>{typeof o=="string"&&o.startsWith("--")&&t.push(o)};n(e.flag);for(let o of e.aliases??[])n(o);return t}function we(e,t){let n=t??y(e),o=new Map,i=new Map,s=new Map,a=new Set;for(let r of n){let c=ye(r);if(c.length===0)continue;let l=`--${x(c[0])}`;for(let d of c)q(o,x(d),l),q(i,U(d),l);let u=U(l);s.has(l)||s.set(l,u),r.list===!0&&a.add(l)}return{canonicalByNormalized:o,canonicalByCompact:i,canonicalComparables:[...s.entries()].map(([r,c])=>({canonicalFlag:r,comparable:c})),listCanonicalFlags:a}}function K(e,t){let n=x(e),o=t.canonicalByNormalized.get(n);if(typeof o=="string")return{flag:o,reason:"flag_alias",confidence:"high"};let i=n.replace(/-/g,""),s=t.canonicalByCompact.get(i);if(typeof s=="string")return{flag:s,reason:"flag_alias",confidence:"high"};let a=i.length>=8?2:1,r=Number.POSITIVE_INFINITY,c,l=!1;for(let u of t.canonicalComparables){let d=I(i,u.comparable,a);if(d!==null){if(d<r){r=d,c=u.canonicalFlag,l=!1;continue}d===r&&c!==u.canonicalFlag&&(l=!0)}}return!c||l||!Number.isFinite(r)||r<=0?null:{flag:c,reason:"flag_typo",confidence:r>=2?"medium":"high"}}function at(e){let t=[`${e}s`];return e.endsWith("y")&&e.length>1&&t.push(`${e.slice(0,-1)}ies`),t}function Ie(e,t=!1){if(t||e.includes("://"))return null;let n=e.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!n)return null;let o=n[1],i=n[3];return i.length===0?null:{key:o,value:i}}function _e(e,t,n=!1){if(n||!e.startsWith("--"))return{tokens:[e]};let o=e.indexOf("="),i=o>=0?e.slice(0,o):e,s=o>=0?e.slice(o+1):void 0,a=K(i,t);if(!a)return{tokens:[e]};let r=s===void 0?a.flag:`${a.flag}=${s}`;return r===e?{tokens:[e]}:{tokens:[r],event:{from:e,to:[r],reason:a.reason,confidence:a.confidence}}}function ve(e){let t=new Set,n=!1;for(let o=0;o<e.length;o+=1){if(n){t.add(o),n=!1;continue}let i=e[o];n=i==="--path"||i==="--pm-path"}return t}function Ce(e){if(!e.startsWith("--"))return null;let t=e.indexOf("=");return t<0?{flag:e}:{flag:e.slice(0,t),inlineValue:e.slice(t+1)}}function ke(e,t,n){n.push(e[t]);let o=e[t+1];return typeof o=="string"&&o!=="--"?(n.push(o),t+2):t+1}function xe(e,t,n,o){if(n.inlineValue!==void 0)return{originalTokens:[e[t]],value:n.inlineValue,consumed:1};let i=[],s=t+1;for(;s<e.length&&e[s]!=="--"&&!e[s].startsWith("-")&&(i.length===0||o.has(n.flag));)i.push(e[s]),s+=1;let a=i.length===0?1:1+i.length;return{originalTokens:e.slice(t,t+a),value:i.length===0?void 0:i.join(","),consumed:a}}function Te(e,t,n,o){let i=e.get(n);if(i){i.values.push(o.value),i.occurrences+=1;return}e.set(n,{outputIndex:t.length,originalTokens:o.originalTokens,values:[o.value],occurrences:1}),t.push(null)}function Ee(e,t){let n=[],o=[];for(let[i,s]of e){if(!(s.occurrences>=2||t.has(i)&&s.originalTokens.length>2)){o.push({outputIndex:s.outputIndex,tokens:s.originalTokens});continue}let r=`${i}=${s.values.join(",")}`;o.push({outputIndex:s.outputIndex,tokens:[r]}),n.push({from:`${i} (x${s.occurrences})`,to:[r],reason:"list_merge",confidence:"high"})}return{events:n,splices:o}}function Se(e,t){t.sort((n,o)=>o.outputIndex-n.outputIndex);for(let n of t)e.splice(n.outputIndex,1,...n.tokens)}function Ae(e,t,n=new Set,o=new Set){if(t.size===0)return{argv:[...e],events:[]};let i=[],s=new Map,a=0;for(;a<e.length;){let l=e[a];if(l==="--"){i.push(...e.slice(a));break}if(n.has(l)){a=ke(e,a,i);continue}let u=Ce(l);if(!u||!t.has(u.flag)){i.push(l),a+=1;continue}let d=xe(e,a,u,o);if(d.value===void 0){i.push(l),a+=d.consumed;continue}Te(s,i,u.flag,{originalTokens:d.originalTokens,value:d.value}),a+=d.consumed}let{events:r,splices:c}=Ee(s,o);return Se(i,c),{argv:i,events:r}}var Y=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function Oe(e,t){if(e!=="test"||t.length<2)return!1;let n=t[t.length-1],o=t[t.length-2],i=Y.get(o);return i!==void 0&&i.has(n)}function Pe(e,t){return e==="search"||Oe(e,t)}function Ne(e,t,n){if(t!=="test")return e;let o=[],i=0;for(;i<e.length;){let s=e[i];if(s==="--")return o.push(...e.slice(i)),o;let a=Y.get(s),r=a?e[i+1]:void 0;if(!a||typeof r!="string"||!a.has(r)){o.push(s),i+=1;continue}let c=i+2;for(;c<e.length&&!e[c].startsWith("-");)c+=1;if(c-(i+2)!==1){o.push(s),i+=1;continue}let l=e[i+2],u=`${r}=${l}`;o.push(s,u),n.push({from:`${s} ${r} ${l}`,to:[s,u],reason:"bare_key_value",confidence:"high"}),i+=3}return o}function Le(e,t,n,o){let i=[],s=ve(e);for(let a=0;a<e.length;a+=1){let r=e[a];if(r==="--"){i.push(...e.slice(a));break}let c=s.has(a),l=i[i.length-1];if(r.startsWith("--")){let d=_e(r,t,c);i.push(...d.tokens),d.event&&o.push(d.event);continue}let u=Ie(r,c);if(u&&!(typeof l=="string"&&l.startsWith("-"))&&!Pe(n,i)){let d=K(u.key,t);if(d){let g=[d.flag,u.value];i.push(...g),o.push({from:r,to:g,reason:"bare_key_value",confidence:d.confidence});continue}}i.push(r)}return i}function Me(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--verify"){let o=e[t+1];if(o===void 0||o==="--")throw new h("history attest --verify requires a bundle file.",p.USAGE);e.splice(t,2,`--verify=${o}`)}else(w.has(n)||n==="--output"||n==="--hash-algorithm")&&(t+=1)}}function ct(e){let t=[],n=ge(e,t),o=me(n);(o.length!==n.length||o.some((T,J)=>T!==n[J]))&&t.push({from:n.join(" "),to:[...o],reason:"legacy_extension_action",confidence:"high"});let i=be(o,t),s=W(i);if(s.conflict)throw new h("Provide the item id either positionally or with --id, not both.",p.USAGE);s.changed&&t.push({from:`--id ${s.itemId}`,to:[s.itemId],reason:"item_id_alias",confidence:"high"});let a=de(s.argv),r=X(s.argv),c=m(r??a??""),l=we(r??a),u=Le(s.argv,l,c,t),d=Ne(u,c,t),g=Ae(d,l.listCanonicalFlags,w,a==="create"?new Set(["--tags"]):new Set);for(let T of g.events)t.push(T);return r==="history attest"&&Me(g.argv),{argv:g.argv,commandName:a,trace:t}}function X(e){let t=j(e),n=t[0]?.trim().toLowerCase(),o=t[1]?.trim().toLowerCase(),i=P(t);return i?i.canonical:(n==="extension"||n==="package"||n==="packages")&&typeof o=="string"&&o.length>0&&!o.startsWith("-")?`${n} ${o}`:n}function lt(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--type"){let o=e[t+1];if(typeof o=="string"&&o.trim().length>0)return o.trim();continue}if(n.startsWith("--type=")){let o=n.slice(7).trim();if(o.length>0)return o}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f7274c6-547e-5590-b7c9-a4d6418bf860")}catch{}})();function Z(e){return e.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function mt(e){if(!(!Array.isArray(e)||e.length===0))return v(e)}function Fe(e,t){let n=Z(t);if(!n)return;let o=y(e).find(i=>i.flag===n||i.aliases?.includes(n));return o?o.value_type==="boolean"?null:`<${o.value_name??"value"}>`:"<value>"}function ht(e,t,n){let o=[...e],i=o.indexOf("--"),s=i<0?o.length:i;for(let a of n){let r=Z(a);if(!r||o.slice(0,s).some(u=>u===r||u.startsWith(`${r}=`)))continue;let c=Fe(t,r),l=c?[r,c]:[r];o.splice(s,0,...l),s+=l.length}return o.length===e.length?void 0:$(o)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bd9a8d3b-bc6f-5309-a3fb-7e5f41ef9dab")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bdf3dec8-63d1-5ea6-a413-64be0ae8f69f")}catch{}})();function vt(e){return e instanceof h||e instanceof Error?e.message:"Unknown failure"}function De(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ve(e){let t=Math.trunc(e);return t>p.SUCCESS?t:p.GENERIC_FAILURE}function Ct(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function kt(e,t){if(e instanceof Error)return e;let n=new Error(t),o=De(e);return o!==void 0&&(n.exitCode=Ve(o)),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]="d22b586a-5c12-518e-b1ee-4baa0d04243b")}catch{}})();function At(e){if(e===void 0)return()=>{};let t=e.trim();if(t.length===0)throw new h("--author requires a non-empty value.",p.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});let n=D();_(t);let o=!1;return()=>{o||(o=!0,n===void 0?_(void 0):_(n))}}import{Command as $e}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a8da6368-489f-579a-8a64-a9bb025f95e7")}catch{}})();function Lt(e){return new $e().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(e).showHelpAfterError(!1).allowExcessArguments(!1).allowUnknownOption(!1).configureOutput({writeOut:t=>{B(t)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the read-output encoding").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include the machine-readable row selector and TOON encoding contract").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="925e5fec-4cc0-5315-a331-03cb128893f0")}catch{}})();var Be={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function H(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" "),s=Be[o]?.indexOf(m(n));if(s!==void 0&&s>=0)return s;if(n===o)return 10;if(i.includes(o))return 11;if(i.some(c=>c.startsWith(o)))return 12;let a=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let c of i){let l=I(c,o,a);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?20+r:n.includes(o)?30:Number.POSITIVE_INFINITY}function Vt(e,t){return e.map(n=>({path:n,score:H(n,t)})).filter(n=>Number.isFinite(n.score)).sort((n,o)=>n.score!==o.score?n.score-o.score:n.path===o.path?0:n.path<o.path?-1:1).map(n=>n.path)}function $t(e,t,n){let o=new Set(t),i=E.filter(r=>r.lifecycle==="deprecated").slice().sort((r,c)=>c.alias.length-r.alias.length),s=[],a=e.flatMap(r=>{let c=i.find(u=>r===u.alias||r.startsWith(`${u.alias} `)),l=r;if(c){let u=r.slice(c.alias.length);if(!o.has(`${c.canonical}${u}`))return[];l=`${c.canonical_argv.join(" ")}${u}`}return n!==void 0&&H(r,n)<10&&s.push(l),[l]});return[...new Set(s.length>0?s:a)]}export{f as a,Q as b,ee as c,Ue as d,G as e,W as f,le as g,j as h,ue as i,k as j,de as k,rt as l,me as m,at as n,Ae as o,Ne as p,ct as q,lt as r,mt as s,Fe as t,ht as u,vt as v,De as w,Ve as x,Ct as y,kt as z,At as A,Lt as B,H as C,Vt as D,$t as E};
2
+ //# sourceMappingURL=chunk-WLJJ4MAU.js.map